https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

voben

08/13/2019, 8:17 PM
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

rook

08/13/2019, 8:23 PM
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

voben

08/13/2019, 8:28 PM
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

Lou Morda

08/13/2019, 8:33 PM
cancel it in onCleared()?
v

voben

08/13/2019, 8:35 PM
cancel already gets called onCleared
👍 1
l

louiscad

08/13/2019, 8:50 PM
Blocking code is not cancellable, unless you go into a specific (and complicated) integration with coroutines cancellation.
👍 1
r

reline

08/13/2019, 9:08 PM
Use
isActive
to check if the coroutine is not cancelled before performing some action
l

louiscad

08/13/2019, 9:13 PM
withContext
already checks for cancellation on enter and exit
r

reline

08/13/2019, 9:32 PM
Yeah, I meant after his blocking operation he could check before
println()
j

Jonathan Walsh

08/13/2019, 11:17 PM
couldn't you also add checks for
isActive
inside the
longRunningCalculation()
if that is doing CPU work and not just blocked on IO?
d

Dominaezzz

08/13/2019, 11:37 PM
isActive
only works in suspend functions, although you could pass in the context I guess.
l

louiscad

08/14/2019, 6:20 AM
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

Dominaezzz

08/14/2019, 10:39 AM
Tomato/Tomato. 😛
3 Views