【问题标题】:Collect Flows in Service收集服务中的流
【发布时间】:2022-07-17 03:48:02
【问题描述】:

所以,我试图在 onCreate() 中从我的前台服务 (LifecycleService) 中的流中收集数据,但在第一次回调之后,它没有提供新数据。

代码是:

    override fun onCreate() {
        super.onCreate()

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

【问题讨论】:

  • 使用lifecycleScope.launch而不是lifecycleScope. launchWhenStarted,因为我们已经在repeatOnLifecycle内部传递STARTED状态
  • 我试过了,但同样的问题

标签: android service kotlin-coroutines foreground-service kotlin-flow


【解决方案1】:

因为observeCoinsPrices() 中使用的流不重播最新值(重播

【讨论】:

  • 我正在片段中收集相同的流,它在那里工作正常。
【解决方案2】:

如果不冻结应用程序,我无法让lifecycleScope.launchLifecycleService.onCreate 方法中工作,所以我所做的是将收集器移到我用来启动服务的方法中,将作业分配到属性,所以我可以在服务被销毁时取消它

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()
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-07
    • 2014-09-13
    • 2018-06-17
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多