Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
           }
      }
 }
like image 481
Wafi_ck Avatar asked Jan 30 '26 17:01

Wafi_ck


1 Answers

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.

like image 158
Sergey Avatar answered Feb 01 '26 05:02

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!