Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import androidx.lifecycle.LiveData
  2. import com.google.firebase.firestore.DocumentSnapshot
  3. import com.google.firebase.firestore.FirebaseFirestore
  4. import com.google.firebase.firestore.ListenerRegistration
  5. import com.google.firebase.firestore.QuerySnapshot
  6.  
  7. /**
  8. * Custom [LiveData] to works with [FirebaseFirestore] snapshots
  9. *
  10. * @param collection The current collection's name
  11. * @param transformer Transform [DocumentSnapshot] to [T]
  12. * @param query Query conditions
  13. */
  14. class FirestoreLiveData<T : Any>(
  15. private val collection: String,
  16. private val transformer: Transformer<T>,
  17. private val query: (CollectionReference.() -> Query)? = null
  18. ) : LiveData<List<T>>() {
  19.  
  20. interface Transformer<T> {
  21. fun transform(document: DocumentSnapshot): T
  22. }
  23.  
  24. /**
  25. * Firebase Firestore
  26. */
  27. private val db by lazy { FirebaseFirestore.getInstance() }
  28.  
  29. /**
  30. * Snapshot listener
  31. */
  32. private var listener: ListenerRegistration? = null
  33.  
  34. override fun onActive() {
  35. subscribe()
  36. }
  37.  
  38. override fun onInactive() {
  39. unSubscribe()
  40. }
  41.  
  42. /**
  43. * Subscribe to snapshot updates
  44. */
  45. private fun subscribe() {
  46. unSubscribe()
  47.  
  48. listener = db.collection(collection)
  49. .run {
  50. query?.invoke(this) ?: this
  51. }
  52. .addSnapshotListener { querySnapshot, firebaseFirestoreException ->
  53. querySnapshot?.let(this::onSnapshotGot)
  54. }
  55. }
  56.  
  57. private fun onSnapshotGot(snapshot: QuerySnapshot) {
  58. value = snapshot.documents.mapNotNull {
  59. try {
  60. transformer.transform(it)
  61. } catch (error: Throwable) {
  62. error.printStackTrace()
  63. null
  64. }
  65. }
  66. }
  67.  
  68. /**
  69. * Unsubscribe from updates
  70. */
  71. private fun unSubscribe() {
  72. listener?.remove()
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement