Title
k

kirillrakhman

03/15/2017, 9:55 AM
@elizarov does kotlinx-couroutines have a mechanism for automatically unsubscribing observables, e.g. when the enclosing activity finishes?
e

elizarov

03/15/2017, 10:12 AM
It is not automatic (we cannot automatically know what activity the coroutines you are launching belong to), but it is very easy to achieve. It is outlined in the guide on UI programming with coroutines. https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md
👍 1
k

kirillrakhman

03/15/2017, 10:27 AM
@elizarov I'll play around with it. I'm especially interested in how to integrate with libraries live Navi or RxLifecycle so that my activities/fragments don't have to implement
JobHolder
or similar.
Does this look ok?
fun NaviComponent.launch(event: Event<*> = Event.DESTROY, block: suspend CoroutineScope.() -> Unit) {
    val job = Job()
    addListener(event) { job.cancel() }
    launch(job + UI, block = block)
}
this looks even simpler:
fun NaviComponent.launch(event: Event<*> = Event.DESTROY, block: suspend CoroutineScope.() -> Unit) {
    val job = launch(UI, block = block)
    addListener(event) { job.cancel() }
}
e

elizarov

03/15/2017, 11:08 AM
Yes. You can just cancel the resulting job on destroy when you are doing it that way
d

deviant

03/15/2017, 11:10 AM
the trick with
job+UI
is actually pretty cool. you can achieve same behavior with dummy job as with rxlifecycle events Publish object that doing signals on each lifecycle event. so just add
job.cancel()
to your BaseActivity onStop() i've also done this convenient helper method specifically for activities and fragments:
fun async(block: suspend CoroutineScope.() -> Unit) {
        launch(UI + job, block = block)
    }
k

kingsley

03/15/2017, 11:21 AM
@kirillrakhman I have a similar setup. I have a job I pass around for any coroutines I create within activity/fragment or any life cycle component. I simply cancel the job l, which cancels everything altogether when the component is going away. I have something like
class Dispatcher {
  fun ui(job: Job) = UI + job
  fun io(job: Job) = CommonPool + job
...
}
Perhaps, there's a better way to approach this? 🤔