Reputation: 1391
I'm a newbie in RxJava and the MVP structure in general. I have more experience using Firebase RTDB the traditional way and now I'm wondering how to best adapt it as a RemoteDataSource (ex TaskRemoteDataSource). In the other MVP examples I would just use callback.onTaskLoaded(task), but with the example contract requiring a return of a Flowable.
Coming from the callback-world of Firebase query and writes. I'm wondering what is the best practice for handling Firebase callback with RxJava. Upon searching github there are N RxFirebase libraries that seems to work but I'm not sure which one to couple my project with. Thank you.
Upvotes: 1
Views: 880
Reputation: 1265
SO the way I use RxJava wrapped round Firebase RTD or Firestore, well in this case Firestore is in the following way. Let's say you would like to retrive data from Firestore (The ideas is pretty much the same with the RTD, just use the realtime database instead)
/**
* Retrieves a document snapshot of a particular document within the Firestore database.
* @param collection
* @param document
* @return
*/
@Override
public Observable<DocumentSnapshot> retrieveByDocument$(String collection, String document) {
//Here I create the Observable and pass in an emitter as its lambda paramater.
//An emitter simply allows me to call onNext, if new data comes in, as well as catch errors or call oncomplete.
///It gives me control over the incoming data.
Observable<DocumentSnapshot> observable = Observable.create((ObservableEmitter<DocumentSnapshot> emitter) -> {
//Here I wrap the usual way of retrieving data from Firestore, by passing in the collection(i.e table name) and document(i.e item id) and
//I add a snapshot listener to listen to changes to that particular location.
mFirebaseFirestore.collection(collection).document(document)
.addSnapshotListener((DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) -> {
if(e != null) {
//If there is an error thrown, I emit the error using the emitter
emitter.onError(e);
}else{
//If there is a value presented by the firestore stream, I use onNext to emit it to the observer, so when I subscribe I receive the incoming stream
emitter.onNext(documentSnapshot);
}
});
});
//I finally return the observable, so that I can subscribe to it later.
return observable;
}
Upvotes: 2