Last active
May 18, 2020 07:28
-
-
Save PatilShreyas/1ae626c2a8d0e4fd04ccaa71739f265a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.shreyaspatil.firebase.coroutines.utils | |
import com.google.firebase.firestore.CollectionReference | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.cancel | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.flow.callbackFlow | |
@ExperimentalCoroutinesApi | |
fun CollectionReference.getSnapshotFlow() = callbackFlow { | |
// Register listener | |
val listener = addSnapshotListener { snapshot, exception -> | |
offer(snapshot) | |
// If exception occurs, cancel this scope with exception message. | |
exception?.let { | |
cancel(it.message.toString()) | |
} | |
} | |
awaitClose { | |
// This block is executed when producer channel is cancelled | |
// This function resumes with a cancellation exception. | |
// Dispose listener | |
listener.remove() | |
cancel() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getPostsRealtime() : Flow<State<List<Post>>> = mPostsCollection.getSnapshotFlow().map { snapshot -> | |
if (snapshot != null && !snapshot.isEmpty) { | |
State.success(snapshot.toObjects(Post::class.java)) | |
} else { | |
State.failed<List<Post>>("No Posts!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment