我如何在Kotlin中编写承诺序列?
作者:互联网
是否可以仅使用Kotlin编写promise(或任务)的序列?
例如,JavaScript中的promise序列写为:
const SLEEP_INTERVAL_IN_MILLISECONDS = 200;
const alpha = function alpha (number) {
return new Promise(function (resolve, reject) {
const fulfill = function() {
return resolve(number + 1);
};
return setTimeout(fulfill, SLEEP_INTERVAL_IN_MILLISECONDS);
});
};
const bravo = function bravo (number) {
return new Promise(function (resolve, reject) {
const fulfill = function() {
return resolve(Math.ceil(1000*Math.random()) + number);
};
return setTimeout(fulfill, SLEEP_INTERVAL_IN_MILLISECONDS);
});
};
const charlie = function charlie (number) {
return new Promise(function (resolve, reject) {
return (number%2 == 0) ? reject(number) : resolve(number);
});
};
function run() {
return Promise.resolve(42)
.then(alpha)
.then(bravo)
.then(charlie)
.then((number) => {
console.log('success: ' + number)
})
.catch((error) => {
console.log('error: ' + error);
});
}
run();
每个具有异步处理结果的功能also returns a Promise,都将由紧随其后的承诺来解决/拒绝.
我知道如何使用RxKotlin编写此代码,但我试图弄清楚如何使用coroutines library或任何其他标准功能编写它.
解决方法:
正如您提到的,coroutines是要使用的标准功能.
如果函数将被挂起,则必须使用suspend关键字,例如IO,或者如果您调用其他暂停函数,例如延迟.
错误处理可以通过普通的try-catch语句完成.
import kotlinx.coroutines.delay
import java.lang.Exception
import kotlin.math.ceil
const val SLEEP_INTERVAL_IN_MILLISECONDS = 200
suspend fun alpha(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return number + 1
}
suspend fun bravo(number: Int): Int {
delay(SLEEP_INTERVAL_IN_MILLISECONDS)
return ceil(1000 * Math.random() + number).toInt()
}
fun charlie(number: Int): Int =
number.takeIf { it % 2 == 0 } ?: throw IllegalStateException(number.toString())
suspend fun run() {
try {
val result = charlie(bravo(alpha(42)))
println(result)
} catch (e: Exception) {
println(e)
}
}
suspend fun main() {
run()
}
如果您喜欢一种更具功能性的错误处理风格,可以这样做:
suspend fun run() {
runCatching { charlie(bravo(alpha(42))) }
.onFailure { println(it) }
.onSuccess { println(it) }
}
标签:kotlin,kotlinx-coroutines,android 来源: https://codeday.me/bug/20191108/2007958.html