dave08
11/22/2018, 8:32 PMlaunchInScope
function to do the same thing... just wondering if that's really the intention. If so, why not just abstract away the whole Job concept and let the end user deal only with scopes?louiscad
11/23/2018, 8:57 AMlaunch
, you already can have a `try`/`catch` block, and the scope in which launch
is called can be a supervisor or have a SupervisorJob()
, so you should never need something like launchInScope
.dave08
11/23/2018, 10:26 AMlouiscad
11/23/2018, 10:37 AMasync
is designed to cancel its scope so other work is cancelled. It is basically a fail fast technique. If you don't put it in a local coroutineScope { … }
, it will cancel the upper scope, possibly without a way to recover. supervisor is to stop cancellation propagation, which is suitable for base scopes like the ones you would have in a UI component, at the root server code, etc…dave08
11/23/2018, 10:40 AMlouiscad
11/23/2018, 10:44 AM<http://play.kotl.in|play.kotl.in>
, <http://try.kotl.in|try.kotl.in>
or locally on your machine:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
suspend fun main() {
coroutineScope {
println(1)
val channel = actor<Int> {
consumeEach {
try {
println("Attempting to do work for $it")
coroutineScope {
val stuff1 = async {
check(it != 2)
it
}
delay(100)
stuff1.await()
}
println("Work done for $it")
} catch (e: IllegalStateException) {
println("Caught it!")
}
}
}
repeat(5) {
channel.send(it)
}
launch {
delay(1000)
println(2)
}
println(3)
println(4)
delay(2000)
channel.close()
}
println(5)
}
Run it and see the IllegalStateException
being caught successfully.
Then, remove the inner coroutineScope { … }
and run again -> see it fail.
Then, replace the outer coroutineScope { … }
with supervisorScope { … }
and run again -> see it fail, with limited propagation.dave08
11/23/2018, 10:48 AMdave08
11/25/2018, 11:26 AMlouiscad
11/25/2018, 11:27 AMlouiscad
11/25/2018, 11:28 AMdave08
11/25/2018, 11:28 AMdave08
11/25/2018, 11:29 AMlouiscad
11/25/2018, 11:29 AMdave08
11/25/2018, 11:30 AMlouiscad
11/25/2018, 11:30 AMsupervisorScope
in place of the OUTER coroutineScope
dave08
11/25/2018, 11:30 AMlouiscad
11/25/2018, 11:31 AMlouiscad
11/25/2018, 11:32 AMdave08
11/25/2018, 11:32 AMlouiscad
11/25/2018, 11:32 AMdave08
11/25/2018, 11:33 AMdave08
11/25/2018, 11:33 AMdave08
11/25/2018, 11:34 AMlouiscad
11/25/2018, 11:35 AMlouiscad
11/25/2018, 11:37 AMdave08
11/25/2018, 11:38 AMdave08
11/25/2018, 11:39 AMlouiscad
11/25/2018, 11:39 AMdave08
11/25/2018, 11:40 AMlouiscad
11/25/2018, 11:43 AMasync
dave08
11/25/2018, 11:46 AMlouiscad
11/25/2018, 1:14 PMSupervisorJob()
is in LifecycleOwners, and ViewModels (for Android apps) so a coroutine can be cancelled without preventing new ones from being launched afterwards