与Firebase身份验证一起使用时,无法访问SuspendCoroutine代码



我的存储库中有一个suspendCoroutine,我想用它将数据发送回我的ViewModel-

suspend fun sendPasswordResetMail(emailId: String): Boolean {
return withContext(Dispatchers.IO) {
suspendCoroutine { cont ->
firebaseAuth?.sendPasswordResetEmail(emailId)
?.addOnCompleteListener {
cont.resume(it.isSuccessful)
}
?.addOnFailureListener {
cont.resumeWithException(it)
}
}
}
}

但是,两个侦听器都没有被调用。调试器表示,在"cont.resume(it.isSuccessful("或"cont.resumeWithException(it("所在的行未找到可执行代码。

我试过"Dispatchers.IO"、"Dispatchers.Main"one_answers"Dispatchers.Default",但似乎都不起作用。我可能做错了什么?

我的ViewModel代码-

isEmailSent : LiveData<Boolean> = liveData {
emit(firebaseAuthRepo.sendPasswordResetMail(emailId))
}

碎片-

viewModel.isEmailSent.observe(viewLifecycleOwner, { flag ->
onResetMailSent(flag)
})

我相信您正在呼叫

isEmailSent : LiveData<Boolean> = liveData {
emit(firebaseAuthRepo.sendPasswordResetMail(emailId))
}

每次发送电子邮件时都有这段代码和

viewModel.isEmailSent.observe(viewLifecycleOwner, { flag ->
onResetMailSent(flag)
})

这件作品只有一次。

假设这是真的,你基本上观察到的是用模型创建的初始实时数据,而每次调用resent时都会替换它。而是调用

isEmailSent.postValue(firebaseAuthRepo.sendPasswordResetMail(emailId))

在一次郊游中。

另外,对于调试器没有显示任何内容,请尝试在cont.resume调用和cont.resumeWithException调用上方添加日志,因为它过去对我有效。

我认为实现这一点的更简单方法是使用firebase-ktxawait()函数(它可以做你正在尝试的事情(:

suspend fun sendPasswordResetMail(emailId: String): Boolean {
try {
firebaseAuth?.sendPasswordResetEmail(emailId).await()
return true
} catch(e: Exception) {
return false
}
}

另一种方法是使用流量:

suspend fun sendPasswordResetMail(emailId: String): Boolean = flow<Boolean {
firebaseAuth?.sendPasswordResetEmail(emailId).await()
emit(true)
}.catch { e: Exception -> handleException(e) }

然后,通过将代码放入视图模型中并调用.asLiveData(),您可以在片段中观察到这一点

最新更新