Created
July 21, 2017 00:16
-
-
Save hbmartin/fa48c26fd1c78941bdcea7079ef612c7 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
public class FirebaseStreamingLiveData<T> extends LiveData<T> { | |
private final Query query; | |
private final Class clazz; | |
public FirebaseStreamingLiveData(Query query, Class<T> clazz) { | |
this.query = query; | |
this.clazz = clazz; | |
} | |
void setSnapshot(DataSnapshot dataSnapshot) { | |
setValue((T) dataSnapshot.getValue(clazz)); | |
} | |
ChildEventListener childListener = new ChildEventListener() { | |
@Override | |
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { | |
setSnapshot(dataSnapshot); | |
} | |
@Override | |
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { | |
setSnapshot(dataSnapshot); | |
} | |
@Override | |
public void onChildRemoved(DataSnapshot dataSnapshot) { | |
// Log.d(TAG, "onChildRemoved: " + dataSnapshot.getKey()); | |
} | |
@Override | |
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { | |
// Log.d(TAG, "onChildMoved: " + dataSnapshot.getKey()); | |
} | |
@Override | |
public void onCancelled(DatabaseError databaseError) { | |
// Log.w(TAG, "onCancelled: ", databaseError.toException()); | |
} | |
}; | |
@Override | |
protected void onActive() { | |
query.addChildEventListener(childListener); | |
} | |
@Override | |
protected void onInactive() { | |
if (!hasActiveObservers()) { | |
query.removeEventListener(childListener); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment