Link CoroutineScope to multiple scopes/jobs

Dear people! I am trying to create a CoroutineScope based observer. My idea is that an object can be observable, within a certain CoroutineScope, and it should have observers that run within a certain scope as well, and execute their code in the given scope (to make it thread/coroutine friendly).

In general I think coroutines can be used to make an Android application life cycle friendly, because of the new extension functions that for example add a lifecycleScope to a LifecycleOwner, which gets cancelled in onDestroy. With a combination of this and the scope of the observable, it should be possible to create an observer that lives and dies with the object it observes, as well as lives and dies with the life cycle. It can mimmick the LiveData from Android, by only allowing changes when the life cycle is in a started state.

I dumped the idea here: ScopedObserver/ScopedObserver.kt at master · joost-klitsie/ScopedObserver · GitHub

I was hoping that I could do something like this:

class Observer: CoroutineScope {
    override val coroutineContext = parentContext + lifecycleOwner.lifecycleScope.coroutineContext + Dispatchers.Main.immediate
}

Where when the parentContext gets cancelled, my observer gets cancelled, and when the lifecycleScope gets cancelled, my observer also gets cancelled. Sadly, this doesn’t work like this, as I am guessing it will take the Job of the last context that is provided as a parent, and then the observer will either be cancelled from the parent context or the lifecycleScope depending how they are ordered.

So now I have this:

init {
    lifecycleOwner.lifecycleScope.launch {
        suspendCancellableCoroutine<Unit> {
            it.invokeOnCancellation {
                this@LifeObserver.cancel()
            }
        }
    }
}

override val coroutineContext = parentContext + Dispatchers.Main.immediate

Where the observer is cancelled if the parent is cancelled, and I basically observe the lifecycleScope by adding a suspendCancellableCoroutine coroutine which will cancel the observer if that one gets cancelled. Is there a better way to do this?