I have just migrated an Android project to use the new structure for coroutines, by implementing CoroutineScope in my Activities and Fragments to properly bind coroutines to their lifecycle. I followed this example.
A couple doubts came up in my mind:
-
Is
CoroutineScope.coroutineContextgetter called at every coroutine creation? Isn’t computing the returnedCombinedContextan expensive operation? I wondered if using an assignement instead of a getter could be better in certain cases: I found that using the same initialJobagain after it’s been canceled doesn’t work, so it makes sense to use the getter and recreate theJobwhen a new lifecycle starts, but wouldn’t it be less expensive to assign it once when we know that it won’t be used again after a cancellation? -
How would you deal with the marvellous Fragment’s double lifecycle? Would it be ok to instantiate two
CoroutineScopes and twoJobs, one for the view lifecycle and one for the instance lifecycle?
Thanks for sharing thoughts and insight!