Created
May 21, 2019 17:53
-
-
Save WaffleLapkin/00938f7c5a2f77bd634c11e0266316b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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