https://kotlinlang.org logo
#android
Title
# android
j

Jiri Malina

04/05/2019, 10:14 AM
Hi, I’m still a bit confused about CoroutineScopes and CoroutineContext. I have a component which launches two coroutines 1. Coroutine which should run even if the user leaves the screen (parses a response from the server and stores the data into the db) 2. Coroutine which is tied to the UI and should be canceled as soon as Android’s ViewModel onClear method is called. I have a couple of questions a) What should I pass to the component - scope or context? b) If I create a context in the ViewModel with
backgroundDispatcher + job
and pass it into the component and I run GlobalScope.launch(context). Will
job.cancel()
cancel it?
a

aballano

04/05/2019, 11:01 AM
for b) I think so, at least is similar to this example here https://github.com/dmytrodanylyk/coroutine-recipes#how-to-launch-a-coroutine
🙏 2
s

sergio250

04/05/2019, 12:35 PM
a) Depending on how you want to create your coroutines, I think the easiest would be to make your component implement CoroutineScope (so that it can use launch/async extensions) and forward the context. For your first coroutine, though, I’d override the context with a different job so that it’s not cancelled when calling
job.cancel()
at the end of your lifecycle b) According to the documentation on
CoroutineScope.launch
yes, the input context will override the one in `GlobalScope`:
The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden with corresponding [coroutineContext] element.
👏 2
j

Jiri Malina

04/05/2019, 12:40 PM
Thank you both for the answers;)!
👌 1