None 以下候选项适用,因为接收器类型不匹配

None of the following candidates is applicable because of receiver type mismatch

我正在迁移旧的 Android 代码库。对于上述代码,我收到以下错误。问题的原因可能是什么?如何轻松解决?

    fun action(action: FunAction) = actor.offer(action)

    private val actor = actor<FunAction>(Dispatchers.Main, Channel.CONFLATED) {

        for (action in this) when (action) {

            is FunAction.Init -> { }

            is FunAction.SaveUserSetting -> { }

            is FunAction.UploadProfilePhoto -> { }

    }

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 

public fun <E> CoroutineScope.actor(context: CoroutineContext = ..., capacity: Int = ..., 
start: CoroutineStart = ..., onCompletion: CompletionHandler? /* = ((cause: Throwable?) -> Unit)? */ = ...,
block: suspend ActorScope<TypeVariable(E)>.() -> Unit): SendChannel<TypeVariable(E)> 
defined in kotlinx.coroutines.channels


错误是因为 actor 函数的签名更改现在定义为 CoroutineScope

上的扩展
public fun <E> CoroutineScope.actor(
    context: CoroutineContext = EmptyCoroutineContext,
    capacity: Int = 0, // todo: Maybe Channel.DEFAULT here?
    start: CoroutineStart = CoroutineStart.DEFAULT,
    onCompletion: CompletionHandler? = null,
    block: suspend ActorScope<E>.() -> Unit
): SendChannel<E>

所以你需要使用一些范围来调用它,你使用哪个范围取决于用例,从ActivityFragment你可以使用lifecycleScope和从ViewModel 你可以使用 viewModelScope 或者你可以使用 GlobalScope 如果你不希望你的 coroutine 被取消,除非你的应用程序被杀死。所以电话看起来像

yourScopeChoice.actor<FunAction>(Dispatchers.Main, Channel.CONFLATED)

请注意

actor 函数由 @ObsoleteCoroutinesApi

标记

这意味着

/** * Marks declarations that are obsolete in coroutines API, which means that the design of the corresponding * declarations has serious known flaws and they will be redesigned in the future. * Roughly speaking, these declarations will be deprecated in the future but there is no replacement for them yet, * so they cannot be deprecated right away. */