How to stop coroutines?

Viewed 57

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())
        }
    }
}
2 Answers

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();
Related