android - 如何封装Android Coroutine Actor并仍然与viewModelScope关联

标签 android kotlin-coroutines

我正在我当前的 Android 项目中调查 Kotlin Coroutine Actors。
目前我有以下类(class)
信使 :

import kotlinx.coroutines.channels.SendChannel
import org.research.development.intentions.action.Sendable

class Messenger<T>(private val sendChannel: SendChannel<T>) : Sendable<T> {

    override suspend fun send(message: T) {
        sendChannel.send(message)
    }
}
查看型号
abstract class BaseViewModel<I, S>(initialState: S) : ViewModel(), ViewModelable<I, S> {

    private val sendChannel: SendChannel<I> = viewModelScope.actor {
        for (message in channel) {
            dispatch(message)
        }
    }

    protected val internalStateFlow = MutableStateFlow(initialState)
    val stateFlow: StateFlow<S>
        get() = internalStateFlow

    private val messenger: Sendable<I> = Messenger(sendChannel)

    override fun send(message: I) {
        viewModelScope.launch(Dispatchers.IO) {
            messenger.send(message)
        }
    }
}
我想要的是在我的 Messenger 类中声明 Actors sendChannel
    import kotlinx.coroutines.channels.SendChannel
    import org.research.development.intentions.action.Sendable
    
    class Messenger<T>() : Sendable<T> {

        private val sendChannel: SendChannel<I> = actor { // viewModelScope????
            for (message in channel) {
                dispatch(message) // HOW DO I CALL THIS METHOD????
            }
        }
    
        override suspend fun send(message: T) {
            sendChannel.send(message)
        }
    }
然而,这给我带来了两个问题
1). My Actor is no longer within my ViewModelScope
2). How do I call the ViewModel Dispatch method
解决问题2)。我可以将调度函数传递给我的 Messenger 类
如何将 Actor 与我的 ViewModelScope 关联?
这整个方法有任何值(value)吗?

最佳答案

您可以通过viewmodelScope在 Messenger 类中并从该范围调用参与者。

private val sendChannel: SendChannel<I> = viewModelScope.actor {
    for (message in channel) {
        dispatch(message) 
    }
}
你也可以覆盖 coroutineContext (我想 Sendable 是 CoroutineScope 的一个子类)
  override val coroutineContext: CoroutineContext
    get() = viewModelScope.coroutineContext

关于android - 如何封装Android Coroutine Actor并仍然与viewModelScope关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63741660/

相关文章:

Android NDK - 应用程序启动时找不到库中的 'extern' 函数

android - 如何在 kotlin 协程上进行指数退避重试

android - RecyclerView 项目未使用 LiveData 更新

android - 无法理解文档中的 Android 示例

java - 如何创建不可删除的通知?

android - 在 onDestroy() 中使用 system.exit(0) (Android)

java - 在 Android Studio 中将 Scala 与 Java 结合使用

android - 如何取消正在运行的 LiveData 协程 block

kotlin - @Around 方面和 Kotlin 挂起函数

kotlin - 将 suspendCancellableCoroutine 转换为callbackFlow