A flow is a type that can emit multiple values sequentially. An addOnSuccessListener
or addOnFailureListener
would emit their results just once. So what you probably want to use is a suspendCancellableCoroutine
builder that can be used for one-shot requests.
Here's what that might look like:
override suspend fun checkIsPostLiked(userId: String, postId: String): FirebaseEventResponse = suspendCancellableCoroutine { continuation ->
try {
FirebaseFirestore.getInstance().collection(postCollection).document(postId).get().addOnSuccessListener {
continuation.resume(SuccessDocument(it), null)
}.addOnFailureListener {
continuation.resumeWithException(ExceptionEvent(it))
}
} catch (e: Exception) {
continuation.resumeWithException(ExceptionEvent(e))
}
}
And you can call it in any coroutine scope (e.g viewModelScope) like so:
viewModelScope.launch {
try {
val isPostLiked = checkIfPostIsLiked(userId, postId)
} catch(e: Exception) {
// handle exception
}
}
Side benefit: You don't have to use the @ExperimentalCoroutinesApi
decorator ;).
EDIT
If you're using await
then you're already using Firestore
with coroutines. So there's no need to use any coroutine builder, just call the suspended function without the addOnSuccessListener
and addOnFailureListener
override suspend fun checkIsPostLiked(userId: String, postId: String): FirebaseEventResponse =
try {
FirebaseFirestore.getInstance()
.collection(postCollection)
.document(postId)
.get()
.await()
} catch (e: Exception) {
// handle exception
}
}