How to transform an Android Task to a Kotlin Deferred?

后端 未结 3 844
夕颜
夕颜 2020-12-09 19:36

Firebase anonymous sign in returns a task (which is basically Google promise implementation):

val task:Task = FirebaseAuth.getInstance().si         


        
3条回答
  •  春和景丽
    2020-12-09 20:18

    Based on this GitHub library, here's a way to transform a Task into a suspending function in the "usual" way to adapt callback based async calls to coroutines:

    suspend fun  Task.await(): T = suspendCoroutine { continuation ->
        addOnCompleteListener { task ->
            if (task.isSuccessful) {
                continuation.resume(task.result)
            } else {
                continuation.resumeWithException(task.exception ?: RuntimeException("Unknown task exception"))
            }
        }
    }
    

    You can also wrap it in a Deferred of course, CompletableDeferred comes in handy here:

    fun  Task.asDeferred(): Deferred {
        val deferred = CompletableDeferred()
    
        deferred.invokeOnCompletion {
            if (deferred.isCancelled) {
                // optional, handle coroutine cancellation however you'd like here
            }
        }
    
        this.addOnSuccessListener { result -> deferred.complete(result) }
        this.addOnFailureListener { exception -> deferred.completeExceptionally(exception) }
    
        return deferred
    }
    

提交回复
热议问题