I'm investigating kotlin coroutines related to Android after 1.0.0 release.
I found tons of examples of making scoped ViewModel (from arch components) with creating parent job and clearing it in onCleared or scoped Activity with job creation in onCreate and clearing in onDestroy (same with onResume and onPause). In some examples I meet this code structure (taken from official docs):
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
Is this custom getter called all times, when we start a new coroutine from this scope? Isn't it bad? Maybe it would be better to keep single scope value instead of creating a new one every time?
[UPDATE]
I accept that solution, if we get rid of lateinit job and create it isntantly, but what if I want to do something like this (what should I do? Is this solution looks like correct or not?):
class LifecycleCrScope: CoroutineScope, LifecycleObserver {
private var _job: Job? = null
override val coroutineContext: CoroutineContext
get() = job() + Dispatchers.Main
fun job() : Job {
return _job ?: createJob().also { _job = it }
}
fun createJob(): Job = Job() // or another implementation
@OnLifecycleEvent(ON_PAUSE)
fun pause() {
_job?.cancel()
_job = null
}
}
val job = Job()and then doval coroutineContext = Dispatchers.Main + jobsince activities should not be created or destroyed more than once (Or useby lazywithcoroutineContext). But how many times per second are youlaunching coroutines? It's just not that important to optimize such a minor operation when you casually do collection operations all the time in ui thread methods.val jobaltogether, you need the job just once inonDestroyand you can get it ascoroutineContext[Job].override val coroutineContext by lazy { Dispatchers.Main + Job() }andcoroutineContext[Job]!!.cancel()to cancel it.