【发布时间】:2021-04-10 11:33:55
【问题描述】:
我是 android 开发的新手,我不知道如何从 Firestore 中返回 Coroutine 中的 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()
}
}
}
请帮我在调用这个函数时返回shareNumber。
【问题讨论】:
-
除非你使用
runBlocking,否则你不能从一个协程返回一个值到一个非挂起函数,这会触发一个ANR错误并且不应该在UI代码中使用。如果需要返回值,请创建函数suspend,并使用CoroutineScope/launch的withContextinsted 来返回值。 -
@Tenfour04 请将此信息添加为答案,因为它描述并提供了非常好的反馈。
-
@Tenfour04 您能否编辑我的代码以更正答案中的一个?谢谢
标签: android function kotlin google-cloud-firestore kotlin-coroutines