RxJava Требуется руководство по реализации Firebase в качестве удаленного источника данных

Я новичок в RxJava и структуре MVP в целом. У меня больше опыта использования Firebase RTDB традиционным способом, и теперь мне интересно, как лучше всего адаптировать его как RemoteDataSource (например, TaskRemoteDataSource). В других примерах MVP я бы просто использовал callback.onTaskLoaded (task), но с примером контракта, требующим возврата Flowable.

Исходя из мира обратного вызова запросов и записей Firebase. Мне интересно, как лучше всего обрабатывать обратный вызов Firebase с помощью RxJava. При поиске в github есть N библиотек RxFirebase, которые, похоже, работают, но я не уверен, с какой из них связать мой проект. Спасибо.


person Andrew Lam    schedule 18.12.2017    source источник


Ответы (1)


Итак, как я использую RxJava, обернутый вокруг Firebase RTD или Firestore, в этом случае Firestore выглядит следующим образом. Допустим, вы хотите получить данные из Firestore (идеи в значительной степени те же, что и с RTD, просто используйте вместо этого базу данных в реальном времени)

    /**
     * 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;
        }
person martinomburajr    schedule 21.12.2017