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()
        }
    }
...
}
scottyab
  • 23,621
  • 16
  • 94
  • 105
  • 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? – Selvin Sep 29 '22 at 09:03
  • 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? – David Wasser Oct 02 '22 at 10:46
  • 2
    @DavidWasser good idea. I've created [this](https://github.com/scottyab/application-lifecycle-observer-sample) 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! – scottyab Oct 03 '22 at 12:08
  • 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. – David Wasser Oct 03 '22 at 17:32

0 Answers0