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
}
}
CodePudding user response:
we will cancel it by job.cancel()
Reference: https://kotlinlang.org/docs/cancellation-and-timeouts.html#asynchronous-timeout-and-resources
Example
var job: Job? = null
job = CoroutineScope(CoroutineName("CR1")).launch {
repository.getStatus(
onSuccess = {
print("onSuccess")
job?.cancel()
},
onFailed = {
print("onFailed")
job?.cancel()
}
}
CodePudding user response:
You can see the below example:
var job:Job=null;
job = coroutineScope?.launch {
if (job.isActive) {
job?.cancelAndJoin()
job = null
}
}
To stop the coroutine you can call below:
job?.cancel();