Kotlin 1.3 & Android: Activities, Fragments and their CoroutineScope implementations

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:

  1. Is CoroutineScope.coroutineContext getter called at every coroutine creation? Isn’t computing the returned CombinedContext 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 initial Job again after it’s been canceled doesn’t work, so it makes sense to use the getter and recreate the Job 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?

  2. How would you deal with the marvellous Fragment’s double lifecycle? Would it be ok to instantiate two CoroutineScopes and two Jobs, one for the view lifecycle and one for the instance lifecycle?

Thanks for sharing thoughts and insight!