Search code examples
androidkotlinkotlin-coroutinesandroid-lifecyclecoroutinescope

How to get lifecycleScope from Context or Activity?


Is it possible to get lifecycle of passed Application or Context?

I need to run background service using Coroutines but already I do simple while(true) which doesn't support lifecycle of my app.

this.applicationContext?.let {
      CoroutineScope(Dispatchers.Default).launch {
           while (true) {
                val fetchedLocation = LocationProvider.getLocationOrNull(it)
                fetchedLocation?.let { location = it }
                delay(1.toDuration(DurationUnit.MINUTES))
           }
      }
 }

Solution

  • lifecycleScope is an extension function on LifecycleOwner, it is defined like the following:

    public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope
        get() = lifecycle.coroutineScope
    

    where lifecycle is an instance of Lifecycle.

    Only Activities and Fragments implement LifecycleOwner, so the lifecycleScope instance can be retrieved only from Activities or Fragments.

    You can create your own implementation of LifecycleOwner and retrieve an instance of lifecycleScope from it.