Reputation: 45
This question gave me a general idea but I'm still struggling.
My fragment -
// Reset email sent observer
viewModel.isEmailSent.observe(viewLifecycleOwner, { flag ->
onResetMailSent(flag)
})
My ViewModel -
val isMailSent: MutableLiveData<Boolean> = MutableLiveData(false)
isEmailSent = liveData {
emit(firebaseAuthRepo.sendPasswordResetMail(emailId))
}
My Repository -
suspend fun sendPasswordResetMail(emailId: String): Boolean {
firebaseAuth?.sendPasswordResetEmail(emailId)
?.addOnCompleteListener {
if (it.isSuccessful) { }
}
?.addOnFailureListener {
}
}
question -
How do I inform the viewmodel that the repo's 'addOnCompleteListener' or 'addOnFailureListener' has been called? I was thinking of returning a boolean flag but seems like I can't place a 'return' statement inside the listeners.
IDE says that the 'suspend' modifier is redundant. Why is that?
Upvotes: 3
Views: 550
Reputation: 21043
You can use suspendCoroutine in this case it will basically work as a hook and you can handle the callback stuff with the Continuation
object. We need this because firebaseAuth
already runs on a separate thread. Try the method below
suspend fun sendPasswordResetMail(emailId: String): Boolean {
return withContext(Dispatchers.IO) {
suspendCoroutine { cont ->
firebaseAuth?.sendPasswordResetEmail(emailId)
?.addOnCompleteListener {
cont.resume(it.isSuccessful)
}
?.addOnFailureListener {
cont.resumeWithException(it)
}
}
}
}
Upvotes: 2