且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在OnCompleteListener Firebase中使用异步/等待/协程

更新时间:2021-12-05 03:48:41

为了摆脱基于回调的API,如下所示:

In order to go from a callback based API like the following one:


val myCallback = object : ServiceCallback() {
    override fun onResult(theobject: Something) {
        // your callback code here
    }
    override fun onFailure(ex: Throwable) {
         // error handling
    }

}

theService.enqueue(callback)

您可以使用 suspendCoroutine

You can use suspendCoroutine

它的作用是暂停执行直到回调满足连续性.因此,您可以编写如下的KTX:

What it does is that it suspends execution until the continuation is satified by the callback. So you can write a KTX like the following:

suspend fun Service.getSomething(): Something = suspendCoroutine{ cont ->
    val callback = object : ServiceCallback(){
         override fun onSuccess(data: Something): Unit = cont.resume(data)
         override fun onFailure(ex: Throwable): Unit = cont.resume(ex)
    }
    this.enqueue(callback)
}