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.coroutineContext
getter called at every coroutine creation? Isn’t computing the returnedCombinedContext
an expensive operation? I wondered if using an assignement instead of a getter could be better in certain cases: I found that using the same initialJob
again after it’s been canceled doesn’t work, so it makes sense to use the getter and recreate theJob
when 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
CoroutineScope
s and twoJob
s, one for the view lifecycle and one for the instance lifecycle?
Thanks for sharing thoughts and insight!