Kotlin Coroutines Delay Job (Synchronized)

May 16, 2018

Behaviour of the following code:

  • Use kotlin coroutines for async task.
  • Schedule a job to run 10 seconds later. If the function is called again before the previous delay/wait complete, it shall reset to wait 10 seconds again.
  • The job is thread-safe and ensure only one "instance" is running.
@Volatile private var backupJob: Job? = null@Synchronized fun scheduleBackupJob() {    Log.d(TAG, "backupJob.schedule")    backupJob?.apply {        // if job still waiting, cancel it        if (isActive) {            cancel()        }    }    // launch job with 10s delay    backupJob = launch {        Log.d(TAG, "backupJob.wait")        delay(10000L)        if (isActive) {            Log.d(TAG, "backupJob.start")            // do something            Log.d(TAG, "backupJob.end")        }        else {            Log.d(TAG, "backupJob.cancel")        }    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.