You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用协程将Repository数据传递到ViewModel及Firebase回调相关问题

问题1 回调结果回传ViewModel的实现方案

Firebase提供的sendPasswordResetEmail是回调式异步API,无法直接在回调内部向外层函数返回值,你可以通过suspendCoroutine将回调封装为挂起函数,就能拿到执行结果返回给ViewModel。修改后的Repository代码如下:

suspend fun sendPasswordResetMail(emailId: String): Boolean = suspendCoroutine { continuation ->
    firebaseAuth?.sendPasswordResetEmail(emailId)
        ?.addOnCompleteListener { task ->
            continuation.resume(task.isSuccessful)
        }
        ?.addOnFailureListener {
            continuation.resume(false)
        }
        ?: continuation.resume(false)
}

修改完成后,ViewModel中liveData构造器调用该方法就能正常拿到布尔返回值,调用emit后Fragment即可观察到对应状态。
注意:你的ViewModel中定义的变量名为isMailSent,但Fragment中观察的变量是isEmailSent,两者需保持命名一致,否则会出现无法观察到状态的问题。

问题2 suspend修饰符冗余的原因

你原始的sendPasswordResetMail函数内部没有调用任何其他挂起函数,也没有任何挂起逻辑,仅给Firebase添加了回调就直接结束执行,suspend修饰符没有实际作用,因此IDE会提示冗余。按上述方案修改为suspendCoroutine封装后,该提示会自动消失。

内容的提问来源于stack exchange,提问作者kk_cc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 01:15:05