Last active
June 29, 2019 22:16
-
-
Save psteiger/f965184d9de081c69cf9acc293f1c1b2 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
open class FirebaseResourceLiveData : LiveData<Resource<DataSnapshot>> { | |
init { | |
value = Resource.Loading() | |
} | |
constructor(path: String) { | |
query = FirebaseDatabase.getInstance().getReference(path) | |
} | |
constructor(ref: DatabaseReference) { | |
query = ref | |
} | |
constructor(query: Query) { | |
this.query = query | |
} | |
private val listener = MyValueEventListener() | |
private val query: Query | |
override fun onActive() { | |
value = Resource.Loading(value?.extractData) | |
query.addValueEventListener(listener) | |
} | |
override fun onInactive() { | |
query.removeEventListener(listener) | |
} | |
private inner class MyValueEventListener : ValueEventListener { | |
override fun onDataChange(dataSnapshot: DataSnapshot) { | |
value = Resource.Success(dataSnapshot) | |
} | |
override fun onCancelled(databaseError: DatabaseError) { | |
val e = databaseError.toException() | |
value = Resource.Failure(e) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment