I'm trying to have a counter using coroutines and not sure if this is the right way to ensure the job and coroutine ends before calling coroutineScope?.cancel()
Is this the correct way and is there a simpler implementation for the same?
class Counter {
private var coroutineScope: CoroutineScope? = null
private var job: Job? = null
private var counter = 0
fun startJob() {
stopJob()
coroutineScope = CoroutineScope(Dispatchers.Main)
job = coroutineScope?.launch {
while (isActive) {
yield()
counter++
delay(2000)
say("counter: ", "$counter")
}
}
}
fun stopJob() {
coroutineScope?.launch {
if (job.isActive) {
job?.cancelAndJoin()
job = null
}
}
coroutineScope?.cancel()
coroutineScope = null
counter = 0
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(Test())
}
}
}