kotlin - 有没有办法在 kotlin 中编写可暂停的委托属性?
问题描述
我试图使用kotlin 提供的特殊功能来实现类似于过程变量的东西。delegate
让我们看以下简单的用例:
- 我有两个变量叫做
var voltage: Float
和var light: Boolean
- 当
voltage
变得大于5.0时,我要开灯 - 当
voltage
变得小于5.0时,我想关灯
注意每个变量的变化都需要发布变化的值(涉及网络调用)
上面的用例在以下代码片段中捕获
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
不支持挂起。
getValue
和setValue
函数 fromReadWriteProperty
是不可暂停的。也不suspend operator getValue()
支持语法。
有没有办法解决这个问题?
我真的不想与使用站点代码妥协。另一件重要的事情,voltage = it
这应该在publishVoltage(n)
调用完成时返回。
解决方案
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.
推荐阅读
- java - JavaFX 中的线程和绑定
- html - Visual Studio WebBrowser 以不同于 IE 的方式呈现网页
- python - 将多个RDD行转换为pyspark中的一行
- mysql - MySQL 从多个表中的列总数中插入(复合?)行
- c - C - 程序为 SEGFAULT 提供了 for 循环,但并非没有
- c# - 如何使用 CodeDom 进行异步调用和函数定义?
- c++ - 用 C++ 编写类型类
- hibernate - 从 DB2 获取 DB2 SQL 错误:SQLCODE=-803, SQLSTATE=23505
- ios - 使用 UISearchBar 时 UITableView 变为 nil
- visual-studio-code - 当我构建项目时,vs-code 突然从 node_modules 弹出“更改”文件