androidkotlinkotlin-coroutineskotlin-android-extensionsandroid-ktx

Kotlin how to launch an async processing from android.app.Application


I am new to Kotlin and trying to start an async backend call inside android.app.Application

import android.app.Application;

class App: Application {

  override fun onCreate() {
    super.onCreate()
    fetchDataFromBackend()
  }

  fun fetchDataFromBackend() {
    lifecycleScope.launch {
      // Fetches data from backed.
    }
  }
}

The problem is that lifecycleScope.launch cannot be used from an Application, I have done the same from Activity/Fragments and viewModelScope for my viewModel.

I wish to do the same inside the Application, does anyone has any suggestions?


Solution

  • You can use ProcessLifecycleOwner, which has the same lifecycle as the Application object.

    ProcessLifecycleOwner.get().lifecycleScope.launch {
      // Fetches data from backend
    }