Collect Flows in Service

Viewed 323

So, I'm trying to collect data from flows in my Foreground service (LifecycleService) in onCreate(), but after the first callback, it is not giving new data.

The code is :

    override fun onCreate() {
        super.onCreate()

        lifecycleScope.launchWhenStarted {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                observeCoinsPrices()
            }
        }
    }
2 Answers

I couldn't get lifecycleScope.launch to work in the LifecycleService.onCreate method without it freezing the app, so what I did instead was moved the collector into a method that I use to start the service, assign the Job into a property so I can cancel it when the Service is destroyed.

import kotlinx.coroutines.Job
//...

class MyService : LifecycleService() {
 //...
 private lateinit var myJob: Job

   // my custom method for starting The Foreground service
   fun startTheService() {
      // call startForeground()
      
      //...

      myJob = lifecycleScope.launch {
          collectFromFlow()
        }
    }

    override fun onDestroy() {
       myJob.cancel()
    }
}

In my case, I was wanting to update text in the foreground notification every time a value was emitted to my Flow collector.

Because Flow used in observeCoinsPrices() not replay the latest value (replay < 1). You should change Flow logic

Related