Skip to content

Instantly share code, notes, and snippets.

@WaffleLapkin
Created May 21, 2019 17:53
Show Gist options
  • Save WaffleLapkin/00938f7c5a2f77bd634c11e0266316b8 to your computer and use it in GitHub Desktop.
Save WaffleLapkin/00938f7c5a2f77bd634c11e0266316b8 to your computer and use it in GitHub Desktop.
private val aMutex = Mutex()
private var job: Job? = null
private fun getJob(from: Int) = launch {
try {
var counter = from
while (isActive) withContext(NonCancellable) {
println(counter++)
delay(100)
}
} catch (e: CancellationException) {
println("end") // graceful shutdown
}
}
suspend fun startWork(from: Int) = aMutex.withLock {
if (job?.isCancelled == false) throw RuntimeException("work already started")
job = getJob(from)
}
suspend fun stopWork() = aMutex.withLock {
if (job == null) throw RuntimeException("work already stoped")
job?.cancel()
job?.join()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment