I am trying to send a network request inside the `...
# coroutines
k
I am trying to send a network request inside the
viewModelScope
while closing the screen. Network request gets canceled as coroutine scope is canceled. How do I send a network request upon closing the screen?
s
The class that runs your network requests should have their own lifecycle. Look at the "Switching CoroutineScopes" section here: https://link.medium.com/gx3HrpwQqkb (a bit of shameless self promotion 😁)
k
If I'd bound it to custom
CoroutineScope
and run network request, does scope cancels itself after all suspend functions are called?
f
You can use
withContext(NonCancellable) {...}
k
What I aim for is do the network request and after that for CoroutineScope to cancel itself. Is this possible?
I suppose this would do the job
Copy code
private var job: Job? = null
    
    job = CoroutineScope(IO).launch {
        networkRequest()
        job!!.cancel()
    }
s
Why would you want the CoroutineScope to cancel itself when the Job is done? In your example, the call to job!!.cancel() doesn't do much. It is called as the last thing in the job, and the job would've ended anyway....why cancel it?
Note that Job != CoroutineScope. When a job ends the CoroutineScope may live on, and be able to launch other jobs at a later time.
k
Ahh
s
Also, depending on your use case, the suggestion from @Francesc is a great one as well.
k
Would having a singleton CoroutineScope make sense then and reuse it for these kind of works?
s
Yup, absolutely. And, if you don't want to have your CoroutineScope cancelled on one request failing (and therefore no longer able to launch future requests), be sure to give it a SupervisorJob().
k
As for a @Francesc answer, does this mean I could run
withContext(NonCancellable)
inside viewModelScope?
👌 1
s
Or better, make the object making these requests a Singleton, and let it have its own CoroutineScope
k
Thanks guys.
s
Be sure to wrap withContext(NonCancellable) around just your network call, not around the call to your UI.
👍 1
k
https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad
Copy code
Whenever you need some work to run beyond its current scope, we recommend creating a custom scope in your Application class and running coroutines within it. Avoid using GlobalScope, ProcessLifecycleOwner scope and NonCancellable for this type of work.
I might go for a singleton CoroutineScope in the end.