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
}
}