:bouquet: An easy way to persist and run code block only as many times as necessary on Android.

Overview

Only

License API API Build Status
Javadoc KotlinWeekly Javadoc

💐 An easy way to persist and run code block only as many times as necessary on Android.

Download

Maven Central Jitpack

Gradle

Add below codes to your root build.gradle file (not your module build.gradle file).

allprojects {
    repositories {
        mavenCentral()
    }
}

And add a dependency code to your module's build.gradle file.

dependencies {
    implementation "com.github.skydoves:only:1.0.8"
}

Usage

Initialize

First, initialize the Only using init() method like below.
This code can be initialized on Application class only once.

Only.init(context)

onDo

Below codes will run the showIntroPopup() only three times using onDo method.

Only.onDo("introPopup", times = 3) {
  showIntroPopup()
}

// kotlin dsl
only("introPopup", times = 3) {
  onDo { showIntroPopup() }
}

Here is the Java codes.

Only.onDo("introPopup", 1, () -> showIntroPopup());

onDone

Below codes will run the doSomethingAfterDone() and toast("done") after run the onDo block codes three times.

Only.onDo("introPopup", times = 3,
  onDo = {
    showIntroPopup()
    toast("onDo only three times")
  },
  onDone = {
    doSomethingAfterDone()
    toast("done")
  })

// kotlin dsl
only("introPopup", times = 3) {
  onDo {
    showIntroPopup()
    toast("onDo only three times")
   }
  onDone {
    doSomeThingAfterDone()
    toast("done")
  }
}

Here is the Java codes.

Only.onDo("introPopup", 1,
    () -> doSomethingOnlyOnce(), // onDo
    () -> doSOmethingAfterDone() // onDone
);

onLastDo, onBeforeDone

We can do pre and post-processing using onLastDo, onBeforeDone options.

only("Intro", times = 3) {
  onDo {
    showIntroPopup()
    toast("onDo only three times")
  }
  onLastDo { // executes only once after finished onDo block 3 times.
    toast("finished onDo")
  }
  onBeforeDone { // executes only once before run onDone block.
    toast("starts onDo")
  }
  onDone {
    doSomethingAfterDone()
    toast("done")
  }
}

We can apply it for repeating x times.
Below codes shows review-popup 3 times and checks the user reviewed or not in onLastDo block.
If not, clear times using the Only.clearOnly method, and repeat it the first time again.

only("Intro", times = 3) {
  onDo { showReviewRequestPopup() }
  onLastDo { // executes only once after finished onDo block 3 times.
    if (!isRequested) {
      Only.clearOnly(this@only.name)
    }
  }
}

Version Control

We can renew the persistence times for controlling the version using version option.
If the version is different from the old version, run times will be initialized 0.

Only.onDo("introPopup", times = 3,
  onDo = { showIntroPopup() },
  onDone = { doSomethingAfterDone() },
  version = BuildConfig.VERSION_NAME // we can set manually. e.g. "1.1.1.1"
)

// kotlin dsl
only("introPopup", times = 3) {
  onDo { showIntroPopup() }
  onDone { doSomethingAfterDone() }
  version("1.1.1.1")
}

Create Using Builder

We can run Only using Only.Builder class like below.

Only.Builder("introPopup", times = 3)
  .onDo { showIntroPopup() }
  .onDone { doSomethingAfterDone() }
  .version(BuildConfig.VERSION_NAME)
  .run()

OnlyOnce, OnlyTwice, OnlyThrice

Here is some useful kotlin-dsl functions.

onlyOnce("onlyOnce") { // run the onDo block codes only once.
  onDo { doSomethingOnlyOnce() }
  onDone { doSomethingAfterDone() }
}

onlyTwice("onlyTwice") { // run the onDo block codes only twice.
  onDo { doSomethingOnlyTwice() }
  onDone { doSomethingAfterDone() }
}

onlyThrice("onlyThrice") { // run the onDo block codes only three times.
  onDo { doSomethingOnlyThrice() }
  onDone { doSomethingAfterDone() }
  version("1.1.1.1")
}

Clear Data

We can optionally delete the stored Only target data or delete the whole Only data.

Only.clearOnly("introPopup") // clears a saved target Only data.
Only.clearAllOnly() // clears all of the target Only data on the application.

View Extension

Below codes will show the button view only once.

button.onlyVisibility(name = "myButton", times = 1, visible = true)

Toast Extension

Below codes will show toast only x times.

onlyToast("toast", 3, "This toast will be shown only three times.")
onlyOnceToast("toast1", "This toast will be shown only once.")
onlyTwiceToast("toast2", "This toast will be shown only twice.")
onlyThriceToast("toast3", "This toast will be shown only thrice.")

Marking

We can mark data to the Only target.

only("introPopup", times = 3) {
  onDo { showIntroPopup() }
  onDone { doSomethingAfterDone() }
  mark("abc") // marks only once when run by kotlin dsl or builder class.
}

Only.mark("introPopup", 3) // changes marking using mark method.
val marking = Only.getMarking("introPopup") // gets the marked data.

Debug Mode

Sometimes on debug, we don't need to persist data and replay onDone block.
onlyOnDoDebugMode helps that ignore persistence data and onDone block when initialization. It runs only onDo block.

val only = Only.init(application)
if (BuildConfig.DEBUG) {
  only.onlyOnDoDebugMode(true)
}

Usage in Java

Here are some usages for Java developers.

int times = Only.getOnlyTimes("IntroPopup") ;
if (times < 3) {
    Only.setOnlyTimes("IntroPopup", times + 1);
    showIntroPopup();
}

Java Supports

we can run Only in our java project.

Only.onDo("introPopup", 1,
    new Runnable() {
  @Override
  public void run() {
    doSomethingOnlyOnce();
  }
}, new Runnable() {
  @Override
  public void run() {
    doSOmethingAfterDone();
  }
});

Or we can run using Only.Builder like below.

new Only.Builder("introPopup", 1)
  .onDo(new Runnable() {
    @Override
    public void run() {
        doSomethingOnlyOnce();     
      }
    })
   .onDone(new Runnable() {
     @Override
     public void run() {
       doSOmethingAfterDone();
     }
   }).run(); // run the Only

Java8 lambda expression

We can make it more simple using Java8 lambda expression.
Add below codes on your build.gradle file.

android {
  compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
  }
}

Then you can run the Only like below.

Only.onDo("introPopup", 1,
    () -> doSomethingOnlyOnce(), // onDo
    () -> doSOmethingAfterDone() // onDone
);

Custom util class

We can create custom util class like what Kotlin's onlyOnce.

public class OnlyUtils {

  public static void onlyOnce(
      String name, Runnable runnableOnDo, Runnable runnableOnDone) {
    new Only.Builder(name, 1)
        .onDo(runnableOnDo)
        .onDone(runnableOnDone)
        .run(); // run the Only
  }
}

Find this library useful? ❤️

Support it by joining stargazers for this repository. ⭐
And follow me for my next creations! 🤩

License

Copyright 2019 skydoves (Jaewoong Eum)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
A Lightweight PDF Viewer Android library which only occupies around 125kb while most of the Pdf viewer occupies up to 16MB space.
A Lightweight PDF Viewer Android library which only occupies around 125kb while most of the Pdf viewer occupies up to 16MB space.

Pdf Viewer For Android A Simple PDF Viewer library which only occupies around 125kb while most of the Pdf viewer occupies upto 16MB space. How to inte

Blinking-image-view - A variant of Android View that blinks only the source image (not the background)

Blinker View for Android What is this? Blinker View is an Android View that blinks a given drawable. Yes, it's that simple. Place it in your layout an

A library for building Java only Zygisk/Riru modules.

A library for building Java only Zygisk/Riru modules.

Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Android app with minimal UI to run snowflake pluggable transports proxy, based on library IPtProxy

Simple Kotlin app for testing IPtProxy's snowflake proxy on Android Essentially a button for starting and stopping a Snowflake Proxy with the default

Run shell commands from a Kotlin script or application with ease
Run shell commands from a Kotlin script or application with ease

Run shell commands from a Kotlin script or application with ease. Turtle simplifies the process of running external commands and processes from your K

Gradle plugin adding a task to run a Paper Minecraft server

Run Paper Run Paper is a Gradle plugin which adds a task to automatically download and run a Paper Minecraft server along with your plugin built by Gr

Run Minecraft on the command line

HeadlessForge While headless Minecraft Clients aren't anything new, they come with a drawback. The Minecraft API is missing and you need to add all fu

Actions are things that run, with parameters. Serves as a common dependency for a variety of Cepi extensions.

Actions Actions that take in customizable paramaters, an optional target, and do things. Installation Download the jar from Releases OR compile it you

Comments
  • Repeat every X times

    Repeat every X times

    I almost wanted to implement the Once library (https://github.com/jonfinerty/Once) until I found your library. The Once has a feature I'd really like to see in Only and that is repeating a task every X times. There can be multiple variants for this feature.

    Variant 1) perform action on the first time (when action has never been performed) and after X times Variant 2) perform action after X times Variant 3) perform action after X times and keep redoing this for Y times or an infinite amount of times

    Examples:

    1. Ask user to rate app after opening the app 10 times, keep asking again after 10 times until the user has rated the app

    2. Notify user about new feature on the app launch and remind them every 10 app startups 2 times (meaning this action is done after 20 app startups)

    3. Keep reminding the user about something every X times for-ever

    I hope you can consider this functionality and for starters just implement the basic one (variant 1 or 2)

    enhancement 
    opened by zunjae 3
  • [FR] Set a time period along with the number of times to do an action

    [FR] Set a time period along with the number of times to do an action

    Is your feature request related to a problem?

    So the thing is, say I want to show a feedback dialog to the user every 2 months and do this for a certain number of times.

    Describe the solution you'd like:

    Set a time period and number of times the dialog should appear.

    Time period = value in duration Count = number

    You can even set exponential backoff for that. Like for example, first 3 counts, it asks every 3 months (the developer sets this time period parameter of course), then once the count is reached, it'll ask every 6 months and so on. Now with de-sugaring, you can incorporate java 8 time libraries for that.

    enhancement 
    opened by ubarua123 5
Releases(1.0.8)
Owner
Jaewoong Eum
Android software engineer. Digital Nomad. Open Source Contributor. ❤️ Love coffee, music, magic tricks and writing poems. Coffee Driven Development.
Jaewoong Eum
Custom ViewPager that allows to block left or right swipe gestures.

SwipeDirectionViewPager Introduction Custom ViewPager that allows to block swiping right or left where the ViewPager child fragments set the scroll di

Jan Rabe 10 Nov 9, 2021
WaxedNotWaxed - Adds a simple indicator to know if a copper block is waxed or not

Waxed Not Waxed Adds a simple indicator to know if a copper block is waxed or no

Mateusz 2 Nov 11, 2022
A library with many useful and easy-to-use features

This library was made as a replacement for qLib and in the future cubed. These 2 plugins are hard to get you hands on and one of them has many outdated methods so this is a more modern version of those things

Max 1 May 6, 2022
An Android app with many challenge modules and SOLID at all

android-super-app An Android app with many challenge modules and SOLID at all. Features Kotlin Coroutines with Flow (State Flow) Kotlin Serialization

Thiago Santos 21 Nov 28, 2022
:performing_arts: An easy, flexible way to implement veil skeletons and shimmering effect for Android.

AndroidVeil An easy, flexible way to implement veil skeletons and shimmering effect for Android. Download Gradle Add below codes to your root build.gr

Jaewoong Eum 1.2k Dec 28, 2022
Simple Android Library, that provides easy way to start the Activities with arguments.

Warning: Library is not maintained anymore. If you want to take care of this library, propose it via Pull Request. It needs adjustmensts for newer ver

Marcin Moskała 429 Dec 15, 2022
:closed_umbrella: An easy way to implement modern permission instructions popup.

Needs An easy way to implement modern permission instructions popup. Needs can be fully customized and showing with animations. Download Gradle Add be

Jaewoong Eum 609 Dec 8, 2022
kinstall is an easy way to install gradle-based command-line kotlin projects that use the application plugin.

kinstall kinstall is an easy way to install gradle-based command-line kotlin projects that use the application plugin. use First, install kinstall its

david kilmer 0 Apr 24, 2022
AdsManager - Easy way to implement Google Ads

AdsManager Easy way to implement Google Ads Implementaion: https://jitpack.io/#R

null 3 Jul 25, 2022
Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs

Zipline This library streamlines using Kotlin/JS libraries from Kotlin/JVM and Kotlin/Native programs. It makes it possible to do continuous deploymen

Cash App 1.5k Dec 30, 2022