【问题标题】:How to use Kotlin async and await for factorials?如何使用 Kotlin 异步并等待阶乘?
【发布时间】:2017-11-03 11:16:08
【问题描述】:

我在 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"
    }

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

【问题讨论】:

  • 您希望factorial 的每个递归调用异步运行(用于实验),还是只在 UI 线程外的协程中运行整个计算?
  • 脱离 UI 线程

标签: android asynchronous kotlin


【解决方案1】:

借助 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

【讨论】:

  • 更新了答案并修复了.await()缺失的错误。
  • 添加 compile "org.jetbrains.anko:anko-coroutines:$anko_version" 后,它说 Failed to resolve org.jetbrains.anko:anko-coroutines:0.9.0。我该怎么办?
  • @AndreiPaciurca 请检查您的项目的repositories { ... }(或allprojects { ... }/subprojects { ... })中是否有jcenter()。另外,最新的 Anko 版本现在是 0.10.2。
  • 有效!不应该是 val 结果: Deferred = bg { factorial(BigInteger(n)) } ?
  • @AndreiPaciurca,确实,Deferred&lt;BigInteger&gt; 是正确的类型,已修复。
猜你喜欢
  • 2019-11-07
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2019-02-21
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多