ViewModelScope is canceling a network request when...
# compose
k
ViewModelScope is canceling a network request when user pops composition where ViewModel is injected. Is it possible to send a network request inside a Side-effects without interruption upon exiting the composition?
c
You can use a NonCancellable job if you have something important that should finish regardless of cancelling the parent job: https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad
a
Use a wider scope for the operation. A common pattern used at the repository layer is to use
.async {}
in a scope owned by the repository to do work, and then await the result in a scope that may cancel when the UI doesn't care anymore. The work will still finish since it's not running in that UI scope, only awaiting a result was.
✔️ 1
Iirc Store does something similar to this https://github.com/dropbox/Store
k
One thing that confuses me in compose is scopes as they are bound to a composition, activity or application. My case would mean that network call should be bound to the parent composition. To create the scope I would have to inject ViewModel into parent just for this purpose.
It also feels that I am breaking SRP, as my parent now has a responsibility of taking care of it's child network request lifetime.
a
A child may not "leak" work that lives longer than it does. To initiate work that outlives itself, the child must accept some object or dependency that can host that work.