Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import androidx.lifecycle.LiveData
- import com.google.firebase.firestore.DocumentSnapshot
- import com.google.firebase.firestore.FirebaseFirestore
- import com.google.firebase.firestore.ListenerRegistration
- import com.google.firebase.firestore.QuerySnapshot
- /**
- * Custom [LiveData] to works with [FirebaseFirestore] snapshots
- *
- * @param collection The current collection's name
- * @param transformer Transform [DocumentSnapshot] to [T]
- * @param query Query conditions
- */
- class FirestoreLiveData<T : Any>(
- private val collection: String,
- private val transformer: Transformer<T>,
- private val query: (CollectionReference.() -> Query)? = null
- ) : LiveData<List<T>>() {
- interface Transformer<T> {
- fun transform(document: DocumentSnapshot): T
- }
- /**
- * Firebase Firestore
- */
- private val db by lazy { FirebaseFirestore.getInstance() }
- /**
- * Snapshot listener
- */
- private var listener: ListenerRegistration? = null
- override fun onActive() {
- subscribe()
- }
- override fun onInactive() {
- unSubscribe()
- }
- /**
- * Subscribe to snapshot updates
- */
- private fun subscribe() {
- unSubscribe()
- listener = db.collection(collection)
- .run {
- query?.invoke(this) ?: this
- }
- .addSnapshotListener { querySnapshot, firebaseFirestoreException ->
- querySnapshot?.let(this::onSnapshotGot)
- }
- }
- private fun onSnapshotGot(snapshot: QuerySnapshot) {
- value = snapshot.documents.mapNotNull {
- try {
- transformer.transform(it)
- } catch (error: Throwable) {
- error.printStackTrace()
- null
- }
- }
- }
- /**
- * Unsubscribe from updates
- */
- private fun unSubscribe() {
- listener?.remove()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement