【问题标题】:How to pass data from repository to ViewModel using coroutine如何使用协程将数据从存储库传递到 ViewModel
【发布时间】:2021-09-07 21:41:38
【问题描述】:

This 的问题给了我一个大概的想法,但我仍在苦苦挣扎。

我的片段 -

// Reset email sent observer
viewModel.isEmailSent.observe(viewLifecycleOwner, { flag ->
    onResetMailSent(flag)
})

我的视图模型 -

val isMailSent: MutableLiveData<Boolean> = MutableLiveData(false)

isEmailSent = liveData {
                emit(firebaseAuthRepo.sendPasswordResetMail(emailId))
            }

我的仓库 -

suspend fun sendPasswordResetMail(emailId: String): Boolean {
   firebaseAuth?.sendPasswordResetEmail(emailId)
               ?.addOnCompleteListener {
                if (it.isSuccessful) { }
               }
               ?.addOnFailureListener {

               }
}

问题-

  1. 如何通知视图模型 repo 的“addOnCompleteListener”或“addOnFailureListener”已被调用?我正在考虑返回一个布尔标志,但似乎我无法在侦听器中放置“返回”语句。

  2. IDE 说 'suspend' 修饰符是多余的。这是为什么呢?

【问题讨论】:

    标签: android kotlin-coroutines android-architecture-components


    【解决方案1】:

    您可以使用suspendCoroutine,在这种情况下,它基本上可以作为一个钩子工作,您可以使用Continuation 对象处理回调内容。我们需要这个,因为firebaseAuth 已经在单独的线程上运行。试试下面的方法

    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.resume(it.isSuccessful)' 或 'cont.resumeWithException(it)' 所在的行没有找到可执行代码。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-11-25
    • 2018-12-25
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多