voben
08/13/2019, 8:17 PMviewModelScope
. 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?
viewModelScope.launch {
doLongRunningOperation()
}
suspend fun doLongRunningOperation() = withContext(Dispatchers.Default) {
longRunningCalculation() // Not a suspending function
println("Hello World")
}
rook
08/13/2019, 8:23 PMwithContext(Dispatchers.Default)
starts your long running operation off of `viewModelScope`’s contextrook
08/13/2019, 8:27 PMsuspend fun doLongRunningOperation() {
longRunningCalculation()
println("HelloWorld")
}
voben
08/13/2019, 8:28 PMLou Morda
08/13/2019, 8:33 PMvoben
08/13/2019, 8:35 PMlouiscad
08/13/2019, 8:50 PMreline
08/13/2019, 9:08 PMisActive
to check if the coroutine is not cancelled before performing some actionlouiscad
08/13/2019, 9:13 PMwithContext
already checks for cancellation on enter and exitreline
08/13/2019, 9:32 PMprintln()
Jonathan Walsh
08/13/2019, 11:17 PMisActive
inside the longRunningCalculation()
if that is doing CPU work and not just blocked on IO?Dominaezzz
08/13/2019, 11:37 PMisActive
only works in suspend functions, although you could pass in the context I guess.louiscad
08/14/2019, 6:20 AMisActive
works on blocking functions too if you have a reference to the CoroutineScope
(usually in a receiver). Can be used in tight loops.Dominaezzz
08/14/2019, 10:39 AM