oday
06/26/2022, 9:34 PMclass DetermineAuthStatus @Inject constructor(
private val firebaseAuth: FirebaseAuth,
private val populateUserPrefs: PopulateUserPrefs
) {
operator fun invoke() = firebaseAuth.currentUser?.let { currentUser ->
val subject = SingleSubject.create<Boolean>()
subject
.hide()
.doOnSubscribe {
currentUser.getIdToken(false)
.addOnSuccessListener { task ->
populateUserPrefs(currentUser, task.token)
subject.onSuccess(true)
}
.addOnFailureListener {
subject.onError(it)
}
}
} ?: Single.just(false)
}
Rick Clephas
06/28/2022, 6:25 AMval currentUser = firebaseAuth.currentUser ?: return false
suspendCoroutine { cont ->
currentUser.getIdToken(false).addOnSuccessListener { task ->
populateUserPrefs(currentUser, task.token)
cont.resume(true)
}.addOnFailureListener {
cont.resumeWithException(it)
}
}
oday
06/28/2022, 1:14 PMval authenticated = determineAuthStatus.invoke()
if (authenticated) do something else do something else?
what about when it’s an exception instead of the boolean im expecting?
do I just place it in a try/catch all the time to make sure i catch these exceptions?Rick Clephas
07/02/2022, 4:43 PMit looks like this “shape” or way of doing it can be suitable for all my usecases that just go out and do something and return something else depending on what it found, or is this something specific to what you saw the original code was doing?Yeah correct you can use
suspendCoroutine
to convert any kind of “single result callback” to a suspend function.
how do I treat this back in where i want to invoke it?What do you mean exactly?
what about when it’s an exception instead of the boolean im expecting?
do I just place it in a try/catch all the time to make sure i catch these exceptions?It depends on the use case, you could return the exception from your suspend function. In that case you should pass it to the
resume
call.
Or you could return Unit
and have the function throw the exception like in my previous example.oday
07/02/2022, 4:59 PMRick Clephas
07/02/2022, 5:03 PMresumeWithException
, which will throw the exception. So you should wrap the call in a try-catch to handle them.oday
07/02/2022, 5:04 PMRick Clephas
07/02/2022, 5:07 PModay
07/02/2022, 5:08 PMRick Clephas
07/02/2022, 5:11 PMfalse
.oday
07/02/2022, 5:15 PMsuspendCoroutine
which you gave me the shortcut to 🙂