LifecycleObserver.onCreate is not called when Application is created
Asked Answered
H

0

6

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()
        }
    }
...
}
Heterogony answered 29/9, 2022 at 8:48 Comment(4)
Did you try to put this into contructor ? ... the point is that there must be some hook to call this ... and this hook is prolly Application.onCreate ... so if you put this after super.onCreate() you will never get DefaultLifecycleObserver.onCreate called ... It is blind guess but after explenation isn't it worth trying?Jenn
Strange. All the examples of how to use ProcessLifecycle seem to indicate that onCreate() should be called. Have you built a small example program to test just this functionality?Pater
@DavidWasser good idea. I've created this sample project/repo. However isolating like this proves the LifecycleOwner API working as expected. So this must be either my user error or something else in our app that's causing an issue. Thanks for the prompt!Heterogony
If you find that you need more help, try to isolate the differences between the sample app and your app and we can try to help you out.Pater

© 2022 - 2024 — McMap. All rights reserved.