Android RxJava需要关于如何实现Firebase作为远程数据源的指导
我是RxJava和MVP结构的新手。我有更多的使用Firebase RTDB的传统方式的经验,现在我想知道如何最好地适应它作为一个RemoteDataSource(ex TaskRemoteDataSource)。在其他MVP示例中,我只使用callback.ontaskloated(task),但是示例契约需要返回一个可流动的Android RxJava需要关于如何实现Firebase作为远程数据源的指导,android,rx-java2,android-mvp,Android,Rx Java2,Android Mvp,我是RxJava和MVP结构的新手。我有更多的使用Firebase RTDB的传统方式的经验,现在我想知道如何最好地适应它作为一个RemoteDataSource(ex TaskRemoteDataSource)。在其他MVP示例中,我只使用callback.ontaskloated(task),但是示例契约需要返回一个可流动的 来自Firebase查询和写入的回调世界。我想知道用RxJava处理Firebase回调的最佳实践是什么。在搜索github时,有N个RxFirebase库似乎可以工作
来自Firebase查询和写入的回调世界。我想知道用RxJava处理Firebase回调的最佳实践是什么。在搜索github时,有N个RxFirebase库似乎可以工作,但我不确定应该将我的项目与哪个库结合起来。谢谢。所以我使用RxJava包装的Firebase RTD或Firestore的方式,在本例中,Firestore采用以下方式。假设您希望从Firestore检索数据(想法与RTD几乎相同,只需使用实时数据库即可)
/**
*检索Firestore数据库中特定文档的文档快照。
*@param集合
*@param文件
*@返回
*/
@凌驾
公共可观察检索ByDocument$(字符串集合,字符串文档){
//在这里,我创建了可观察对象,并将发射器作为其lambda参数传入。
//发射器只允许我在新数据输入时调用onNext,以及捕获错误或调用oncomplete。
///它让我可以控制传入的数据。
可观测的可观测的=可观测的。创建((可观测发射器)->{
//这里,我总结了从Firestore检索数据的常用方法,通过传入集合(即表名)和文档(即项id)以及
//我添加了一个快照侦听器来侦听对该特定位置的更改。
mFirebaseFirestore.collection(collection).document(document)
.addSnapshotListener((DocumentSnapshot DocumentSnapshot,FirebaseFirestoreException e)->{
如果(e!=null){
//如果抛出错误,我将使用发射器发出错误
发射体。onError(e);
}否则{
//如果firestore流提供了一个值,我将使用onNext将其发送给观察者,因此当我订阅时,我将接收传入流
emitter.onNext(documentSnapshot);
}
});
});
//我最终返回了可观察的,以便以后可以订阅它。
可观测收益;
}
/**
* 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;
}