Last active
October 14, 2018 11:55
-
-
Save marcelpinto/262567c750695c20b4f0c8d865fb6360 to your computer and use it in GitHub Desktop.
Example of Firebase LiveData mechanism
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
class FirebaseLiveData<T>( | |
private val reference: DatabaseReference, | |
private val resourceType: Class<T> | |
) : LiveData<Resource<T>>(), ValueEventListener { | |
override fun onActive() { | |
super.onActive() | |
if (value == null) { | |
value = Resource.loading() | |
} | |
reference.addValueEventListener(this) | |
} | |
override fun onInactive() { | |
super.onInactive() | |
reference.removeEventListener(this) | |
} | |
override fun onCancelled(error: DatabaseError) { | |
value = Resource.error(error.message) | |
} | |
override fun onDataChange(data: DataSnapshot) { | |
value = if (!data.exists()) { | |
Resource.error("404 Resource ${resourceType.simpleName} not found") | |
} else { | |
Resource.success(data.getValue(resourceType)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment