I have a long running operation which I start from...
# coroutines
v
I have a long running operation which I start from my
viewModelScope
. When the viewmodel gets destroyed before the long running operation finishes, the function println(“Hello World”) is still getting called. Wouldn’t the coroutine get cancelled and not print “Hello World” due to structured concurrency?
Copy code
viewModelScope.launch {
        doLongRunningOperation()
}

suspend fun doLongRunningOperation() = withContext(Dispatchers.Default) {
        longRunningCalculation() // Not a suspending function
        println("Hello World")
    }
r
I think that your
withContext(Dispatchers.Default)
starts your long running operation off of `viewModelScope`’s context
Copy code
suspend fun doLongRunningOperation() {
  longRunningCalculation()
  println("HelloWorld")
}
v
but I need to run the long running operation off of the main thread. I don’t see why having another Dispatcher would be the issue
l
cancel it in onCleared()?
v
cancel already gets called onCleared
👍 1
l
Blocking code is not cancellable, unless you go into a specific (and complicated) integration with coroutines cancellation.
👍 1
r
Use
isActive
to check if the coroutine is not cancelled before performing some action
l
withContext
already checks for cancellation on enter and exit
r
Yeah, I meant after his blocking operation he could check before
println()
j
couldn't you also add checks for
isActive
inside the
longRunningCalculation()
if that is doing CPU work and not just blocked on IO?
d
isActive
only works in suspend functions, although you could pass in the context I guess.
l
Wrong,
isActive
works on blocking functions too if you have a reference to the
CoroutineScope
(usually in a receiver). Can be used in tight loops.
d
Tomato/Tomato. 😛