android - 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!!)
}
}
}
解决方案
延续 允许您将同步的东西转换为异步的
官方协程代码实验室曾经对此有所了解,但他们似乎已将其删除。样板大致是这样的:
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(...)
}
推荐阅读
- php - Laravel6 Passport accessToken 自定义撤销
- python - 如何使用 deepcopy python/colab
- linux - 更改其他进程中线程的优先级
- python - python中的utf-16转换
- git - 迁移到 GitLab 后可以删除原始仓库吗
- wordpress - 无法在 Wordpress 中归档博客文章
- database - SPARQL 维基数据。如何只选择维基百科数据库,避免笔记重复?
- python - pandas 按多个条件过滤,无需链接
- python - 为什么定义在 NumPy 文档字符串部分的冒号前有一个空格?
- javascript - 创建可定制的水箱可视化