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")
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.