gpt4 book ai didi

android - Android Service中如何使用MutableSharedFlow?

转载 作者:行者123 更新时间:2023-12-05 04:47:57 25 4
gpt4 key购买 nike

我想在服务类中使用 MutableSharedFlow,但我不确定如何在服务结束时停止订阅。如何在服务中实现 MutableSharedFlow 功能或任何其他可用于监听流数据的功能?

最佳答案

要在 android Service 类中使用 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
}
}

关于android - Android Service中如何使用MutableSharedFlow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68279594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com