ir2pid
ir2pid

Reputation: 6166

How to stop coroutines?

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

Upvotes: 1

Views: 106

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 87

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

Upvotes: 1

Shahryar Ahmed
Shahryar Ahmed

Reputation: 307

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

Upvotes: 1

Related Questions