3

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 -

  1. 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.

  2. IDE says that the 'suspend' modifier is redundant. Why is that?

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
kk_cc
  • 45
  • 4

1 Answers1

2

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)
                }
        }
    }
}
ADM
  • 20,406
  • 11
  • 52
  • 83
  • Where do I return the boolean flag? – kk_cc Jun 24 '21 at 12:12
  • `cont.resume(it.isSuccessful)` is the boolean which you will get as return value . Or an exception if fails . – ADM Jun 24 '21 at 12:13
  • Ah, okay. I tried this but now neither of the listeners are called. Debugger says no executable code found at line where 'cont.resume(it.isSuccessful)' or 'cont.resumeWithException(it)' is. – kk_cc Jun 24 '21 at 12:18
  • This worked in one instant. We are Resigning the job. :) Thanks. – Nitin Tej May 03 '22 at 11:32