如何在Android服务中使用MutableSharedFlow



我想在Service类中使用MutableSharedFlow,但我不知道如何在Service结束时停止订阅。如何在服务中实现MutableSharedFlow函数或任何其他可用于侦听流数据的函数?

要在androidService类中使用Flow,我们需要一个CoroutineScope实例来处理启动协程和取消。请参阅以下代码和我的评论:

class CoroutineService : Service() {
private val scope = CoroutineScope(Dispatchers.IO)
private val flow = MutableSharedFlow<String>(extraBufferCapacity = 64)
override fun onCreate() {
super.onCreate()
// collect data emitted by the Flow
flow.onEach {
// Handle data
}.launchIn(scope)
}
override fun onStartCommand(@Nullable intent: Intent?, flags: Int, startId: Int): Int {
scope.launch {
// retrieve data from Intent and send it to Flow
val messageFromIntent = intent?.let { it.extras?.getString("KEY_MESSAGE")} ?: ""
flow.emit(messageFromIntent)
}
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder?  = null
override fun onDestroy() {
scope.cancel() // cancel CoroutineScope and all launched coroutines
}
}

相关内容

  • 没有找到相关文章

最新更新