Created
July 19, 2017 05:52
-
-
Save hbmartin/680eafd1e63993ede9528a231fd963e3 to your computer and use it in GitHub Desktop.
This file contains 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
import android.arch.lifecycle.LiveData; | |
import android.support.annotation.WorkerThread; | |
import com.google.firebase.database.DataSnapshot; | |
import com.google.firebase.database.DatabaseError; | |
import com.google.firebase.database.DatabaseReference; | |
import com.google.firebase.database.ValueEventListener; | |
public class FirebaseLiveData<T> extends LiveData<Resource<T>> { | |
private final DatabaseReference dbRef; | |
private final Class clazz; | |
public FirebaseLiveData(DatabaseReference dbRef, Class<T> clazz) { | |
this.dbRef = dbRef; | |
this.clazz = clazz; | |
setValue(Resource.loading(null)); | |
} | |
@WorkerThread | |
public void init() { | |
dbRef.addListenerForSingleValueEvent(new ValueEventListener() { | |
@Override | |
public void onDataChange(DataSnapshot dataSnapshot) { | |
setValue(Resource.success((T) dataSnapshot.getValue(clazz))); | |
} | |
@Override | |
public void onCancelled(DatabaseError databaseError) { | |
setValue(Resource.error(databaseError.getDetails(), null)); | |
} | |
}); | |
} | |
ValueEventListener updateListener = new ValueEventListener() { | |
@Override | |
public void onDataChange(DataSnapshot dataSnapshot) { | |
setValue(Resource.success((T) dataSnapshot.getValue(clazz))); | |
} | |
@Override | |
public void onCancelled(DatabaseError databaseError) { | |
setValue(Resource.error(databaseError.getDetails(), null)); | |
} | |
}; | |
@Override | |
protected void onActive() { | |
dbRef.addValueEventListener(updateListener); | |
} | |
@Override | |
protected void onInactive() { | |
if (!hasActiveObservers()) { | |
dbRef.removeEventListener(updateListener); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment