gpt4 book ai didi

android - 如何使用 Kotlin async 并等待阶乘?

转载 作者:行者123 更新时间:2023-11-30 00:17:02 25 4
gpt4 key购买 nike

我在 Kotlin(Android 应用)中有这个功能:

tailrec fun factorial(n: BigInteger, remainder: BigInteger = BigInteger.ONE) : BigInteger{
if(n== BigInteger.ZERO)
return remainder
else {
return factorial(n - BigInteger.ONE, remainder * n)
}
}

和这个简单的代码:

button.setOnClickListener {
val n = editTextT.text.toString()
val result: BigInteger = factorial(BigInteger(n))
textView.text = "$n! is $result"
}

我的问题是:有没有办法以异步方式进行这种计算?如果是,如何?

最佳答案

有了 Anko 对协同程序的支持(在 this article 中描述),您可以运行一个协同程序,它在 UI 线程中执行代码,但在后台运行和等待操作,在您的情况下它看起来像:

button.setOnClickListener {
val n = editTextT.text.toString()
async(UI) {
val result: Deferred<BigInteger> = bg { factorial(BigInteger(n)) }
textView.text = "$n! is ${result.await()}"
}
}

另请参阅:Anko reference

关于android - 如何使用 Kotlin async 并等待阶乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com