How do you guys handle coroutines in android, whic...
# coroutines
u
How do you guys handle coroutines in android, which want to outlive the viewmodel scope? should repository or whatever does the couroutine have its scope, and be transparent to the viewmodel or should that scope be passed into the viewmodel and viewmodel launches the coroutine into that scope?
o
the scope should be tied to some lifecycle, so probably the repository should have it, if it is the one that should own the coroutines
u
okay, but how can I make it composable in the viewmodel?
Copy code
fun Service.doWhatever() {
    serviceScope.launch {
    ...
    }
}
fun ViewModel.buttonClick() {
   viewModelScope.launch {
       service.doWhatever()
       ui.displaySuccess()
   }
}
in this ssample ui.displaySuccess wont wait for the coroutine
o
then it probably shouldn't be in its own scope? that particular coroutine doesn't need to outlive the VM scope
u
why not? say its posting a chat message, you still want the post to finish without cancel, when you switch screens, no?
o
sounds like you need an application level scope then, that the original launch occurs on. in this case, the Service does not want to own the coroutine, but the application as a whole
u
thats no difference in this case as Service is singleton, anyways where would your app scope live? or rather where its going to be used, in service or vm?
o
I'm not sure, I'm not very familiar with android. I would use it in the VM, because that's the UI area
u
so youd pass the appScope via ctor to the vm?
o
yea
u
okay, but, now viewmodel decides the scope, is that smart? client code basically dictating the lifecycle implicitly?
o
I'm not sure about the particular design pattern pros/cons, this appears to be reasonable to me because the action is supposed to outlive the VM in this case, so you want whatever creates it to pass something in, since it (the creator) typically has a longer lifecycle than the VM
u
yea but why not hide it inside the Service, or whatever holds the coroutine .. I mean for viewmodel, viewmodelScope is also private in the VM, view which has even shorter lifecycle, doesnt see it
o
it doesn't make sense to me, because then the service would be calling out to the UI
u
what do you mean? viewmodel.scope { service.foo; ui.display }
o
then that's still on the VM scope, right?
u
well, that was my argument, that each component that has a lifecycle, should have its own scope
service -> viewmodel -> view
each have their lifecycle, narrowing to the right
o
well, it doesn't make sense, because the outer coroutine is what needs to be launched on it
so you still need to pull it out of the service
u
well, why then the view doesnt own the scope if its the actual callsite?
o
because then it should be cancelled when the view is closed, right?
u
also,
Copy code
fun Viewmodel.buttonClick {
   appScope.launch {
      service.foo()
      ui.display
   }
}
doesnt this leak Ui?
o
yes, it does leak it until the coroutine finishes
there isn't much you can do to avoid that, it would leak regardless
u
well yes, and you dont want that cancelation, hence you move the scope ownership upstream
o
that's not a thing in coroutines afaik
where you launch it, is what scope it is tied to
u
so how would I jump that?
I dont feel like UI should decide lifecycle of some mutating business logic
o
I suppose you could pass some event back and forth in this case
the trick is that, imo, the service shouldn't directly call the UI either
u
yea sure, service has no knowledge about ui
okay so if that function will be nonsuspending, and launching a coroutine inside its service scope, how can I let the result go outside? channel?
but that breaks composability doesnt it?
o
really, I haven't run in to this case myself, so I'm not sure what is the best/better design option. I think what I originally proposed is the best fit for this scenario, UI should dictate service lifecycle because it needs to run something after it.
u
how about that leak though? thats not cool
o
do you expect it to not "leak"?
how else will the UI object be around for when it finishes?
I would not consider it a leak, because you really do want it to stay around for later
u
well youre keeping the ui in memory after it should be destroyed / gced
o
no, because you wanted to call it
did you not want that at the end of the coroutine?
u
I did, but when ui is gone, its no longer necessary. Why im beating at this is that with rxjava you can do this via autoConnect, downstream just unsubscribes, upstream keeps chugging
o
okay, but when that
launch
block finishes... UI is GC'd
it doesn't stick around after the coroutine is done
k
Copy code
suspend fun Service.doWhatever() {
}
fun ViewModel.buttonClick() {
   viewModelScope.launch {
       service.doWhatever()
       ui.displaySuccess()
   }
}
Couldn't you do something like this?
o
the issue is that the coroutine should stick beyond VM, whereas this will be cancelled when the VM is closed
k
I see. Seems like you would start the service on it's own and then send an event back to a listener (in this case the ViewModel) that the data is ready. If the ViewModel's lifecycle is done, it would unsubscribe and not be notified
u
Well yes, but youre comunicating via listener / channel / rx observsble, i.e. composability of suspend functions is gone, right?, also the listener needs to be keyed to identify that call if need be, etc. im not super happy about that
g
If you want to avoid cancellation of service operation, it should be one of two: 1. implementation details of service, which never cancel operation, so just run it on own scope (for example by launching async) and awaits it already on caller's scope (just suspend function) 2. call site runs operation with NonCancellable context, but careful with second approach, it's relatively easy to leak coroutine
u
1. how would that look like?
Copy code
suspend fun foo() {
    val deffered = scope.async {
      // foo stuff
    }
    return deffered.await
}
this?
g
yes, like this
Check this example https://pl.kotl.in/peLtoh5bh
u
sorry that opens my previous snippet and a helloworld in incognito mode
g
Yeah, looks like some bug of playground. Try this one: https://pl.kotl.in/wdzhx7_IY
u
Yea that I had in mind, however have you seen this?
Copy code
If you need to launch a coroutine that keeps running after your function returns, then make your function an extension of CoroutineScope or pass scope: CoroutineScope as parameter to make your intent clear in your function signature. Do not make these functions suspending:
https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055
g
It's an explicit way to do this, as I said, it depends on what is your goal. If you just do this on-call site, of course, use different more global scope, how was already suggested in this thread if it actually services logic (do not lose requests even if client is cancelled) and you do not want to add this logic on every client, then do this on level of service, it doesn't violate structured concurrency
And what you cited is not really your case, because you want to wait for result