5

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()
            }
        }
    }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Ankit Gupta
  • 512
  • 1
  • 6
  • 19

2 Answers2

1

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.

lasec0203
  • 2,422
  • 1
  • 21
  • 36
  • Services run in the main thread and lifecycleScope launches coroutines in the main thread as well. Did you try switching context by changing the dispatcher to io or default? – Eury Pérez Beltré Jul 27 '23 at 10:28
0

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