LifecycleObserver.onCreate is not called when Application is created

726 Views Asked by At

We have a task that is run when the Application is created and we're trying to move the code from our Application object's onCreate to their own Lifecycle aware classes. I'm added my ApplicationLifecycleAwareTaskRunner (a LifecycleObserver) to the lifecycle of the ProcessLifecycleOwner in Application.onCreate() but it's onCreate(owner: LifecycleOwner) is never called. The onStart(..) and onStop() are called as expected.

Is this a known limitation of LifecycleObserver that it cannot observe Application.onCreate() events? or is there something I'm missing here?

Using androidx.lifecycle:lifecycle-runtime-ktx:2.4.1

Adding the observer in the Application object.

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        // DI and other init

       ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleAwareTaskRunner(..))
    }
}

The task runner:

class ApplicationLifecycleAwareTaskRunner(
    private val appCoroutineScope: CoroutineScope,
    private val myTask: MyTask
) : DefaultLifecycleObserver {

    // This is never called :( 
    override fun onCreate(owner: LifecycleOwner) {
        appCoroutineScope.launch {
            myTask.invoke()
        }
    }
...
}
0

There are 0 best solutions below