kotlin - 有没有可以在 Dart 中编写像 Future&then 这样的挂起函数的函数?
问题描述
飞镖中的示例代码:
void main() {
step1().then(step2).then(step3).then(print);
}
Future<String> step1() async {
return Future.value("setp1");
}
Future<int> step2(String input) async {
return Future.value(input.length);
}
Future<bool> step3(int input) async {
return Future.value(input > 3);
}
有没有办法像这样在kotlin中编写代码?
我使用flow写了一个简单的代码,但我找不到简化它的方法
suspend fun step1(): String {
return "step1"
}
suspend fun step2(input: String): Int {
return input.length
}
suspend fun step3(input: Int): Boolean {
return input > 3
}
suspend fun execute() {
flowOf(step1())
.map { step2(it) }
.map { step3(it) }
.collect { print(it) }
}
解决方案
kotlin 协程没有采用类似 Promise 的 API(then/map/flatMap),因为有了挂起功能,这可以更容易地完成
import kotlinx.coroutines.delay
import kotlinx.coroutines.yield
suspend fun main(args: Array<String>) {
val one = step1()
val two = step2(one)
val three = step3(two)
println(three)
}
suspend fun <T> resolve(value: T): T {
yield() // to simulate Future.resolve
return value
}
suspend fun step1() = resolve("100")
suspend fun step2(input: String) = resolve(input.length)
suspend fun step3(input: Int) = resolve(input > 3)
见下面的讨论
推荐阅读
- c# - 可以打开上传到blob容器的excel文件吗?
- ruby - 基于 Rails 和 mongoid 中的项目管理用户角色
- json - 如何在 Oracle 18c 中创建手动 JSON?
- ios - Swift 4.2 编译器无法导入使用 Swift 4.0.3 编译的模块
- ios - “致命错误:在使用 JSON 的 Swift 上展开可选值时意外发现 nil”
- angular - 在 stackblitz 中向 Angular 应用程序添加测试用例时出错
- yaml - GitLab CI/CD 通用配置
- node.js - 具有多个字段的 $lookup
- postgresql - Docker Compose 在 Crunchy Postgres 和 Hasura Graphql 引擎上 - 数据库 URL 设置
- selenium - Jenkins 插件在测试构建期间显示文件