Nurseyit Tursunkulov
Nurseyit Tursunkulov

Reputation: 9380

how to collect flow from one place and cancel from another?

I have a flow:

fun startCountingTimer(coroutineContext: CoroutineContext, leftSeconds: Int): Flow<Int> {
return flow {
    for (i in leftSeconds downTo 0) {
        delay(1000)
        emit(i)
    }
 }
}

I want to collect it from one place :

startWaitingTimer().collect {
    ...
}

and cancel from another:

startWaitingTimer().cancel()

How to do it?

Upvotes: 1

Views: 202

Answers (1)

gladed
gladed

Reputation: 1743

Use launchIn to return a Job. When you're done, cancel the job.

val job = startWaitingTimer(10).onEach { ... }.launchIn(scope)

// Later...
job.cancel()

Upvotes: 1

Related Questions