如何从 CoroutineScope Kotlin 返回一个整数?

And*_*cre 0 android function kotlin google-cloud-firestore kotlin-coroutines

我是 android 开发的新手,我不知道如何从 firestore 返回协程中的 int ......

这是我的函数代码:

    fun getSharesNumber(context: Context, name:String) = CoroutineScope(Dispatchers.IO).launch {
        try {
            var trade1:Trade
            var sharesNumber:Int
            tradesCollectionRef.document(name)
                .get()
                .addOnSuccessListener {
                        trade1 = it.toObject(Trade::class.java)!!
                            sharesNumber = trade1.shares
                    }.await()
        }catch (e:Exception){
            withContext(Dispatchers.Main){
                Toast.makeText(context,"$e",Toast.LENGTH_LONG).show()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮助我在调用此函数时返回 shareNumber。

Ten*_*r04 5

除非使用runBlocking,否则不能将协程中的值返回到非挂起函数,这可能会触发 ANR 错误并且永远不应在 UI 代码中使用。如果需要返回值,则使函数挂起,并使用/withContext代替CoroutineScope/launch返回必须在后台线程上计算的值。

suspendCoroutine当您使用的库已经提供await()挂起功能时,您不需要使用。由于await是挂起函数,因此您也不必使用特定的调度程序调用它,也不需要处理回调,因此您的代码可以变为:

suspend fun getSharesNumber(context: Context, name:String): Int {
    return try {
        tradesCollectionRef.document(name).get().await()
            .toObject(Trade::class.java)?.shares
            ?: error("Document $name doesn't exist.")
    } catch (e:Exception){
        withContext(Dispatchers.Main){
            Toast.makeText(context, "$e", Toast.LENGTH_LONG).show()
        }
        -1
    }
}
Run Code Online (Sandbox Code Playgroud)

如果失败,它将返回 -1。或者,您可以让它抛出异常并在更高处捕获它。不过,对于失败返回 null 而不是抛出更符合 Kotlin 习惯。我没有测试这个,因为我不使用 Firestore,所以语法可能会稍微偏离。