首页 > 解决方案 > 有没有可以在 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) }
}

标签: kotlindart

解决方案


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)

见下面的讨论

https://github.com/Kotlin/kotlinx.coroutines/issues/342


推荐阅读