首页 > 解决方案 > 有没有办法在 kotlin 中编写可暂停的委托属性?

问题描述

我试图使用kotlin 提供的特殊功能来实现类似于过程变量的东西。delegate

让我们看以下简单的用例:

注意每个变量的变化都需要发布变化的值(涉及网络调用)

上面的用例在以下代码片段中捕获

    suspend fun publishLightStatus(status: Boolean): Unit = TODO()
    suspend fun publishVoltage(voltage: Float): Unit = TODO()

    fun subscribeToVoltage(block: (Float) -> Unit): Unit = TODO()

    var light: Boolean by Delegates.observable(false) { _, _, n ->
        publishLightStatus(n)
    }

    var voltage: Float by Delegates.observable(0F) { _, _, n ->
        if(n > 5.0) light = true
        else if (n < 5.0) light = false

        publishVoltage(n)
    }

    // usage
    subscribeToVoltage {
        voltage = it
    }

上面的代码无法编译,因为当前property delegates不支持挂起。 getValuesetValue函数 fromReadWriteProperty是不可暂停的。也不suspend operator getValue()支持语法。

有没有办法解决这个问题? 我真的不想与使用站点代码妥协。另一件重要的事情,voltage = it这应该在publishVoltage(n)调用完成时返回。

标签: kotlindelegatescoroutinekotlin-coroutines

解决方案


In general properties should be simple and should return quickly. They shouldn't be exposing anything to warrant suspension but that's only an opinion.

There's no way to do this right now but there's a YouTrack issue here and here concerning this.

You could also try using runBlocking or GlobalScope.launch which might suit your needs.


推荐阅读