首页 > 解决方案 > Kotlin Coroutines-Android 中 RXJava 等价物的 Completable.create

问题描述

我正在研究 Firebase 身份验证,其中我需要将 firebase 身份验证放在我的存储库中。我找到了这篇关于如何做到这一点的文章,但它使用了 RxJava。(https://www.simplifiedcoding.net/firebase-mvvm-example/

现在,我想知道是否有唯一的 kotlin 解决方案,因为我不想使用 RxJava,因为我正在使用 kotlin 协程。

fun facebookLogin(credential: AuthCredential) = Completable.create { emitter -> // change Completable.create since it is a RxJava
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener { task ->
        if (!emitter.isDisposed) {
            if (task.isSuccessful)
                emitter.onComplete()
            else
                emitter.onError(task.exception!!)
        }
    }
}

标签: androidkotlin

解决方案


延续 允许您将同步的东西转换为异步的

官方协程代码实验室曾经对此有所了解,但他们似乎已将其删除。样板大致是这样的:

suspend fun facebookLogin(...): Boolean {
  return   suspendCoroutine { continuation -> 
      firebaseAuth.signInWithCredential(credential).addOnCompleteListener { task ->

            if (task.isSuccessful)
                continuation.resume(true)
            else
                continuation.resumeWith(Result.failure(task.exception))
        }
    }
  }  
}

并从 ViewModel 调用它,你会

fun login () {
   viewModelScope.launch{
      facebookLogin(...)
   }
}

如果不在视图模型上,您可以随时

CoroutineContext(Dispatchers.IO).launch{
   facebookLogin(...)
}

推荐阅读