【问题标题】:How to use continues instead of bad callbacks如何使用 continue 而不是坏回调
【发布时间】:2020-05-05 07:37:27
【问题描述】:

我从 Firestone 获取数据,因为不想返回空列表,所以我使用回调 协程更好吗,我有很多这样的,所以在这种情况下回调很吵,async/await 会是一个很好的解决方案

         getHerosFromCloud(object :OnFinishedCallbacks {
             override fun onFinshed(list: List<Any>) {
                 CoroutineScope(Dispatchers.IO).launch {
                     MainDatabase.heroDao.insertAll(*(list as List<Hero>).toTypedArray())

                 }
             }
         })


interface OnFinishedCallbacks {
    fun onFinshed( list:List<Any>)
}


 fun getHerosFromCloud(onFinishedCallbacks: OnFinishedCallbacks)
        {

            val heroList =ArrayList<Hero>()

                   db.collection("Heros")
                .get()
                .addOnSuccessListener { documentSnapshot  ->
                    if (documentSnapshot  != null) {
                        for(heroDoc in documentSnapshot) {
                            heroList.add(heroDoc.toObject(Hero::class.java))
                        }

                        Log.d("newherosNames", "newdoorsNames data: ${heroList}")
                        onFinishedCallbacks.onFinshed(heroList)
                    } else {
                        Log.d("heros", "No such document")
                    }
                }
                .addOnFailureListener { exception ->
                    Log.d("heros", "get failed with ", exception)
                }

        }

【问题讨论】:

标签: android kotlin google-cloud-firestore kotlin-coroutines coroutinescope


【解决方案1】:

据我了解,您希望在使用回调 Api 时使您的代码更加简洁和一致。您可以使用suspendCoroutinesuspendCancellableCoroutine

suspendCoroutine 暂停执行它的协程,直到我们决定通过调用适当的方法 - Continuation.resume... 继续。

suspendCancellableCoroutine 函数,它的行为类似于 suspendCoroutine 的附加功能 - 为块提供 CancellableContinuation 的实现。

对于您的示例,它将如下所示:

suspend fun getHeroesFromCloud() = suspendCoroutine<List<Hero>> { continuation ->
    db.collection("Heros")
        .get()
        .addOnSuccessListener { documentSnapshot  ->
            val heroList = ArrayList<Hero>()
            if (documentSnapshot  != null) {

                for(heroDoc in documentSnapshot) {
                    heroList.add(heroDoc.toObject(Hero::class.java))
                }

                Log.d("newherosNames", "newdoorsNames data: ${heroList}")
            } else {
                Log.d("heros", "No such document")
            }
            continuation.resume(heroList)
        }
        .addOnFailureListener { exception ->
            continuation.resumeWithException(exception)
            Log.d("heros", "get failed with ", exception)
        }

}

// Call this function from a coroutine
suspend fun someFun() {
    val heroes = getHeroesFromCloud()
    // use heroes
}

【讨论】:

  • 也可以使用kotlinx-coroutines-play-services 不必重写。
猜你喜欢
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 2022-01-08
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多