How to transform an Android Task to a Kotlin Deferred?

后端 未结 3 853
夕颜
夕颜 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:09

    The package kotlinx.coroutines.tasks now includes the follwing utility functions:

    public suspend fun  Task.await(): T { ... }
    

    From the docs:

    Awaits for completion of the task without blocking a thread.
    This suspending function is cancellable.
    If the Job of the current coroutine is cancelled or completed while this suspending function is waiting, this function stops waiting for the completion stage and immediately resumes with CancellationException.

    public fun  Task.asDeferred(): Deferred { ... }
    

    From the docs:

    Converts this task to an instance of Deferred.
    If task is cancelled then resulting deferred will be cancelled as well.


    So you can just do:

    suspend fun signInAnonymouslyAwait(): AuthResult {
        return FirebaseAuth.getInstance().signInAnonymously().await()
    }
    

    or:

    fun signInAnonymouslyDeferred(): Deferred {
        return FirebaseAuth.getInstance().signInAnonymously().asDeferred()
    }
    

提交回复
热议问题