Code Monkey home page Code Monkey logo

rxfirebase's Introduction

Stay awhile and listen 📓

Medium LinkedIn Github contact


My name is Francisco Garcia, also known as Durdin. I'm an Android developer from Madrid, Spain 🇪🇸 currently working at @masmovil.

I mainly focus on mobile development using Kotlin, Swift & Java, but I'm also used to work with C, C++, JS, TS or Dart.

I'm a self-taught developer that has grown thanks to all the colleagues I have worked with along the years. Coding is my passion and one of my daily hobbies since I was a kid(thx epic dad!). I survived to an arrow to my knee shot by Clean architectures and now I'm a first line enjoyer of reactive architectures such as Redux & Flux. Be ready for it if you go deep in my repositories 👾.


About me

  • 🔭 I'm currently working on open-source libs, apps and tools that improve Android development.
  • 🔥 I'm a Firebase fanboy. Feel free to reach me if you have any doubt about it!
  • ⚡ Fun facts:
    • I'm a fitness enthusiast.
    • I'm a LARP(Live Action Role Play) player.
    • Netflix stole my image to design Vesemir on The Witcher: Nightmare of the Wolf.
    • FOR THE HORDE!

Open source and contributions

Personal open source projects

Project Platforms Programming Language(s) Latest update Stars PRs Issues
RxFirebase Android Java December 23, 2022
Xcode Intellij Dark Theme macOS July 3, 2020
Xcode Intellij Keybinds macOS July 3, 2020
Code Challenge - Idealista Android January 13, 2020
Code Challenge - Monzo Android Kotlin September 20, 2019
Flurt - Flux architecture Flutter Dart December 7, 2018
World of Warcraft Arena android Kotlin November 15, 2018
Android Push notification Skeleton Android Kotlin May 12, 2018
Firestore TS Cloud functions Android TypeScript November 6, 2017
RxCamera2 Android Java November 22, 2016

Projects I contribute to

Project Platforms Programming Language(s) Latest update Stars PRs Issues
Mini Kotlin Android, Kotlin Kotlin July 1, 2024
Morsa - Jetpack Compose Testing Framework Android Kotlin October 5, 2021
Mini Kotlin 2.0 Android Kotlin March 10, 2021

Some GitHub stats

Who doesn't love some stats?

NOTE: the stats include both public and private repository contributions

Code stats Top Langs

My latest posts

➡️ More posts here

Credits


This README is generated automatically thanks to Github Actions every day

Latest update: Thursday, July 18, 2024, 02:23 AM GMT+2

Latest repo version: 1.0.6

rxfirebase's People

Contributors

edtheguy00 avatar frangsierra avatar gswierczynski avatar m7mdyahia avatar maragues avatar sroka avatar wiyarmir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rxfirebase's Issues

Query multiple documents

You can query for a single document like it shows here :

https://github.com/FrangSierra/RxFirebase#firestore

However what if you want to query for multiple documents and return that in a Maybe<>. How would you go about that?

something like this

validSpotIds.forEach { validSpotId ->
            RxFirestore.getDocument(collectionRef.document(validSpotId.toString()))
                    .map { it.data }
                    .map { it.get("forecasts") }
                    .map { (it as ArrayList<HashMap<String, Object>>)[currentHour] }
                    .filter { (it.get("shape_full") as String).equals("Good")
                            || (it.get("shape_full") as String).equals("Fair-Good")}
                    .doOnSuccess { forecast -> Timber.d("forecast - "+forecast) }
                    .subscribe { spotData -> Timber.d("Finished")}
        }

However i wouldn't want to call subscribe here, i want to build up an rxchain that returns a Maybe.

Is RxFirestore still on beta?

Hi, I am new here and very confused. I saw on some post that Rx2Firebase 1.4 would contain Firestore.. however, the Firestore branch is behind by 10 commits and RxFirestore is there on master. Problem is, it isn't showing here and I'm not sure what is going on:

screen shot 2018-01-25 at 20 09 22

Crash due to NPE in firebase-database

I use firebase realtime database through rxfirebase. Occasionally I get the following crash (not on my devices, but through crashlytics).

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 
   'java.lang.String java.lang.String.toLowerCase(java.util.Locale)' on a null object reference
at com.google.firebase.database.tubesock.WebSocketHandshake.verifyServerHandshakeHeaders(com.google.firebase:firebase-database@@16.0.5:111)
at com.google.firebase.database.tubesock.WebSocket.runReader(com.google.firebase:firebase-database@@16.0.5:418)
at com.google.firebase.database.tubesock.WebSocket.access$000(com.google.firebase:firebase-database@@16.0.5:47)
at com.google.firebase.database.tubesock.WebSocket$2.run(com.google.firebase:firebase-database@@16.0.5:143)
at java.lang.Thread.run(Thread.java:818)

SingleValue source

Thanks for porting this to RxJava2, will be moving my project to use this library soon :)

After using Firebase for some time one of most painful limitations for me was inability to choose source (Cache or Network) for SingleValue listeners after setting
FirebaseDatabase.getInstance().setPersistenceEnabled(true)

This is well described here:
https://stackoverflow.com/questions/35454652/how-to-bypass-the-firebase-cache-to-refresh-data-in-android-app?noredirect=1&lq=1
and here:
https://groups.google.com/forum/#!msg/firebase-talk/ptTtEyBDKls/XbNKD_K8CQAJ

Since firebase team didn't care to acknowledge that this is an issue I guess we have to stick with mock object workaround from first answer on SO link above.

I know that this library is only meant to be a wrapper around Firebase but having overloaded observeSingleValueEvent listener method that lets you specify source would be great. Would you accept PR if I add and properly test this?

io.reactivex.exceptions.OnErrorNotImplementedException

When I signIn with wrong password ,I got the exception below. What's wrong with it? I had call doOnError().

RxFirebaseAuth.signInWithEmailAndPassword(mAuth, email, password).doOnSuccess(new Consumer<AuthResult>() { @Override public void accept(final AuthResult authResult) throws Exception { mView.signInSuccess(authResult.getUser().getDisplayName(), authResult.getUser().getPhotoUrl()); } }).doOnError(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { mView.signInFailed(throwable.getMessage()); } }).subscribe();

io.reactivex.exceptions.OnErrorNotImplementedException: The password is invalid or the user does not have a password.
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
at io.reactivex.internal.operators.maybe.MaybeCallbackObserver.onError(MaybeCallbackObserver.java:81)
at io.reactivex.internal.operators.maybe.MaybePeek$MaybePeekObserver.onErrorInner(MaybePeek.java:147)
at io.reactivex.internal.operators.maybe.MaybePeek$MaybePeekObserver.onError(MaybePeek.java:134)
at io.reactivex.internal.operators.maybe.MaybePeek$MaybePeekObserver.onErrorInner(MaybePeek.java:147)
at io.reactivex.internal.operators.maybe.MaybePeek$MaybePeekObserver.onError(MaybePeek.java:134)
at io.reactivex.internal.operators.maybe.MaybeCreate$Emitter.onError(MaybeCreate.java:94)
at durdinapps.rxfirebase2.RxHandler.onFailure(RxHandler.java:49)
at com.google.android.gms.tasks.zzd$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The password is invalid or the user does not have a password.
at com.google.android.gms.internal.zzblv.zzce(Unknown Source)
at com.google.android.gms.internal.zzbls$zzj.zza(Unknown Source)
at com.google.android.gms.internal.zzbmd.zzcf(Unknown Source)
at com.google.android.gms.internal.zzbmd$zza.onFailure(Unknown Source)
at com.google.android.gms.internal.zzbly$zza.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:453)

calling both on onSuccess() and onComplete() breaks MaybeObserver contract

https://github.com/FrangSierra/Rx2Firebase/blob/a2d4e07d5d68e541c847892f160f263cd18a1388/app/src/main/java/durdinapps/rxfirebase2/RxFirebaseDatabase.java#L94-L99

as stated in MaybeObserver contract
After a MaybeObserver calls a Maybe's subscribe method, first the Maybe calls onSubscribe(Disposable) with a Disposable that allows cancelling the sequence at any time, then the Maybe calls only one of the MaybeObserver's onSuccess(T), onError(java.lang.Throwable) or onComplete() methods to provide notifications.

so I suggest this should be

 public void onDataChange(DataSnapshot dataSnapshot) { 
    if (dataSnapshot.exists()) { 
       emitter.onSuccess(dataSnapshot); 
    } else {
    emitter.onComplete(); 
    }
} 

Firestore

Is there an upcoming Firestore RxJava implementation?

Chain Firestore setDocument operations in offline

Hello, great library! But here is a problem :)

I need to chain Firebase-s setDocument operation in offline, but I can't because library's binding trying to wait till Task's OnSuccessListener will be called.

How can I manage this?

DataSnapShot.value == null

given this sample(in kotlin):

fun getIsLiked(query: DatabaseQuery): Maybe<Boolean>{
    return RxFirebaseDatabase.observeSingleValueEvent(query, 
        {snapShot -> (snapShot.value as Long).toInt() == 1})
}

I had an issue where the value was null. (which happens if it isn't in firebase)
I wasn't able to find a work around using this function with a mapper.
Instead, I used the single parameter call and did:

.filter( { snapShot -> snapShot.exists() } )

Not sure if this is by design or not but I don't think an empty DataSnapShot should be emitted?

My suggestion change source from

public void onDataChange(DataSnapshot dataSnapshot) {
    emitter.onSuccess(dataSnapshot);
    emitter.onComplete();
}

to

public void onDataChange(DataSnapshot dataSnapshot) {
    if(dataSnapshot.exists())
        emitter.onSuccess(dataSnapshot);
    emitter.onComplete();
}

Just my 2 cents.

P.S. great library, found this to be most helpful.

Delete event on parent or last child in group

Hi @FrangSierra ,

I'm using your library and I got an issue when a parent is deleted.

Let's say I have this structure in my firebase database :

posts: {
    my_group: {
         key_1: true,
         key_2: true
    }
}

If I observeValueEvent on my_group, if a node is deleted it works. But, if the last node is deleted the onNext is never called (because the key my_group has been deleted by firebase). The same thing happen if the posts or directly the my_group key are deleted (even if there is child in it).

An event is triggered, but there is no data in it so the onNext is never called. From your code :

final ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(final DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                emitter.onNext(dataSnapshot);
            } else {
                // Here, we need to dispatch the info because the root node (or all child) have been potentially deleted.
            }
     }
     ...
};

Do you have an idea to handle this case ?

Edit:

If I remove the dataSnapshot.exists() condition in your code, I get the expected behavior (empty list).

observeSingleValueEvent implementation prevents it to return empty child values

a few days ago I posted this question in StackOverflow:

https://stackoverflow.com/questions/51887649/rxfirebase-observesinglevalueevent-implementation-prevents-it-to-return-empty

for this query I've made:


override fun isFavorite(beerId: String): Observable<Boolean> {
        var task = path.child(beerId)
        return RxFirebaseDatabase.observeSingleValueEvent(task) { t -> map(t) }.toObservable()
    }
    private fun map(t: DataSnapshot): Boolean {
        return (t.value ?: false) as Boolean
    }

It seems that the filter DATA_SNAPSHOT_EXISTENCE_PREDICAT is preventing the result from being mapped:

@NonNull
    public static <T> Maybe<T> observeSingleValueEvent(@NonNull Query query, @NonNull Function<? super DataSnapshot, ? extends T> mapper) {
        return observeSingleValueEvent(query).filter(DataSnapshotMapper.DATA_SNAPSHOT_EXISTENCE_PREDICATE).map(mapper);
    }

at the same time I do not know if I'm doing something wrong or could easily get around this problem somehow, I'm not so skillful in Rx.

Support Firebase Firestore

Hi,

Thank you for your library, it helps a lot :)

Yesterday Google released the Firebase Firestore project (beta). I think it could be very interesting to integrate it in your library too.

subscribe when query is empty

I'm try to get an user profile with multiples nodes of a realtime database with this code:

public static void getUserProfile(String storeId, String userId, final Callback callback){
        DatabaseReference userRef = RealtimeDatabase.getUserRef(userId);
        DatabaseReference addressRef = RealtimeDatabase.getUserAddressRef(userId);
        DatabaseReference contactRef = RealtimeDatabase.getUserContactRef(userId);
        DatabaseReference storeUserRef = RealtimeDatabase.getStoreUserRef(storeId, userId);
        DatabaseReference storeNameRef = RealtimeDatabase.getStoreRef(storeId).child(Store.PARAM_NAME);

        RxFirebaseDatabase.observeSingleValueEvent(userRef, User.class)
            .zipWith(RxFirebaseDatabase.observeSingleValueEvent(addressRef, Address.class), zipUserAddress)
            .zipWith(RxFirebaseDatabase.observeSingleValueEvent(contactRef, UserContact.class), zipUserContact)
            .zipWith(RxFirebaseDatabase.observeSingleValueEvent(storeUserRef, StoreUser.class), zipUserStore)
            .zipWith(RxFirebaseDatabase.observeSingleValueEvent(storeNameRef, String.class), zipUserStoreName)
            .subscribe(new Consumer<User>() {
                @Override
                public void accept(User user) {
                    callback.onSuccess(user);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    throwable.printStackTrace();
                    callback.onError(throwable);
                }
            });

    }

This code works well to a complete profile, but when profile does not have address node or contact node, for example, the function in subscribe is never called and this is a problem for me now. Can you help me?

Firestore collection documents mapping issue

First of all - thanks for a great library!

My problem: querying the Firestore and mapping the resulting documents.

Simplified code in Kotlin:

fun getBatteries(batteryStatus: BatteryStatus): Maybe<List<Battery>> {
        val query = batteriesDb.whereEqualTo("status", batteryStatus.name)

        return RxFirestore.getCollection(query, Battery::class.java)
                .subscribeOn(domainScheduler)
}

On subscription, only the onComplete action is called. After investigation seems like removing the mapping (RxFirestore.getCollection(query)), the onSuccess action is called properly and the resulting QuerySnapshot contains the right documents. If I perform querySnapshot.toObjects(Battery.class), a proper list of batteries is returned.

Any hints on what might be the issue here?

Thanks,
Rafal

Cannot write tests for to mock static RxFirebase methods

One of the issues I am running into is writing tests for code that uses RxFirebase.

In these classes I usually inject FirebaseAuth or whatever and pass it in to the static calls to RxFirebaseAuth. Since the methods in RxFirebaseAuth are static I am not able to mock them out during my tests to return some data of my choice. I can mock out FirebaseAuth itself but it likely will require dealing with some more levels of mocking than I should need to.

Being able to mock out RxFirebaseAuth methods would solve this. I am not sure if that means offering non static methods for this purpose and I am also curious if others have found workarounds to this

Inserting values

Your implementation of updateChildren does not guarantees that children will be inserted if not found. For that, Firebase as a setValue() method which also updates children if found.

How about something like this?

fun setValue(ref: DatabaseReference, value: Any): Completable {
    return Completable.create({ emitter ->
        ref.setValue(value).addOnSuccessListener({ _ ->
            if (!emitter.isDisposed) {
                emitter.onComplete()
            }
        }).addOnFailureListener { e ->
            if (!emitter.isDisposed) {
                emitter.onError(e)
            }
        }
    })
}

I think this will greatly improve observable chainability. Right now and due to the lack of this sort of methods, we cannot chain an insertion event with an update event.

Function signInWithCredential() not completed in success only onCompleted

Hello

I am implementing phone authentication, after successfully implementing it I did it returned a FirebasePermissionDenied error but the second time it seemed to run correctly.

I tried to find out a bug reason what it was happening, and if the responsibility was this library envolve or firebase sdk.

I did the following checks.

Error code
The problem is that I try to write just after the login and in my rules that I have only authenticate users can write. this code throws an error
but why?

 rxFirebaseRepository.signInWithCredential (credential)
                .flatMapCompletable {
              rxFirebaseRepository.setValue (FirebaseDatabase.getInstance (). reference.child (USERS) .child (it.user !!. uid), userMapper.mapToEntity (userModel))
                } .andThen (Single.fromCallable ({userModel}))
  1. Check login status just after signInWithCredential function

FirebaseAuth.getInstance (). CurrentUser == null why?

  1. I tried implementate without this library looking at Google documentation
   mAuth.signInWithCredential (credential)
            .addOnCompleteListener (this, new OnCompleteListener <AuthResult> () {
                @Override
                public void onComplete (@NonNull Task <AuthResult> task) {
                    if (task.isSuccessful ()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d (TAG, "signInWithCredential: success");

                        FirebaseUser user = task.getResult (). GetUser ();
                        // ...
                    } else {
                        // Sign in failed, display a message and update the UI
                        Log.w (TAG, "signInWithCredential: failure", task.getException ());
                        if (task.getException () instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                        }
                    }
                }
            });

This code works correctly, why?

  1. Looking at the differences between the implementation proposed by google and this library.

public class RxHandler <T> implements OnSuccessListener <T>, OnFailureListener, OnCompleteListener <T> {
    private final MaybeEmitter <? super T> emitter;

    private RxHandler (MaybeEmitter <? super T> emitter) {
        this.emitter = emitter;
    }

    public static <T> void assignOnTask (MaybeEmitter <? super T> emitter, Task <T> task) {
        RxHandler handler = new RxHandler (emitter);
        task.addOnSuccessListener (handler);
        task.addOnFailureListener (handler);

        try {
            task.addOnCompleteListener (handler);
        } catch (Throwable var4) {
            ;
        }

    }

    public void onSuccess (T res) {
        if (res! = null) {
            this.emitter.onSuccess (res);
        } else {
            this.emitter.onError (new RxFirebaseNullDataException ("Observables can not emit null values"));
        }

    }

    public void onComplete (@NonNull Task <T> task) {
        this.emitter.onComplete ();
    }

    public void onFailure (@NonNull Exception e) {
        if (! this.emitter.isDisposed ()) {
            this.emitter.onError (e);
        }

    }
}


I think that the problem is that the onSuccess function is called but the task is not completed so I call the writing function and this returns an error FirebasePermissionError

Looking at the documentation it seems that your implementation is correct but something is happening, I´ll leave this here to try to solve this small mystery.

At the moment I created my own envelope to solve this

     return Maybe.create ({em ->
            FirebaseAuth.getInstance (). SignInWithCredential (credential)
                    .addOnCompleteListener {
                        if (it.isSuccessful)
                            em.onSuccess (it.result)
                        else
                            em.onComplete ()
                    } .addOnFailureListener {
                        em.onError (it)
                    }
        })

It seems that everything runs correctly

Regards

Mappers cannot return null in RxJava 2

https://github.com/FrangSierra/Rx2Firebase/blob/master/app/src/main/java/durdinapps/rxfirebase2/DataSnapshotMapper.java#L65

private static class TypedDataSnapshotMapper<U> extends DataSnapshotMapper<DataSnapshot, U> {

      private final Class<U> clazz;

      public TypedDataSnapshotMapper(final Class<U> clazz) {
         this.clazz = clazz;
      }

      @Override
      public U apply(final DataSnapshot dataSnapshot) {
         if (dataSnapshot.exists()) {
            return getDataSnapshotTypedValue(dataSnapshot, clazz);
         } else {
            return null;
         }
      }
}

If dataSnapshot.exists() returns false (the observed child got deleted), the mapper will return null, resulting in an io.reactivex.exceptions.OnErrorNotImplementedException: The mapper function returned a null value. Applies to other mappers as well.

handle exception on signinwithemailandpassword

i can't handle the exception when a user try to login which is not yet created it throws exception even i put in try catch help me to slove this problem hwo i suppose to handle exception thanks in advance

RxFirebaseAuth.signInWithEmailAndPassword(auth, email, password)
.filter(result -> result.getUser() != null)
.subscribe(result -> {
dataSaveRepo.getUserData(result);

                }));

Should observeSingleValueEvent return io.reactivex.Single?

According to addListenerForSingleValueEvent docs

Add a listener for a single change in the data at this location. This listener will be triggered once with the value of the data at the location.

This behavior matches io.reactivex.Single description, where you expect to receive either success or error

I know it's easy to convert to Single, but I think it's conceptually wrong to return Flowable when observing a single value

RxFirebaseDatabase.observeSingleValueEvent(getReference(), Post.class).singleOrError()

Specify Id of document in RXFirestore

Is it possible to specify the id of the documents we create via RXFirestore.addDocument()? I find this very useful feature missing. Could someone help show how to do it?

Cannot get Firestore collection observable

I'm trying to get your library to work. I want to track a collection of objects. I can get my list of objects using the following code:

override fun getPois(): Observable<List<PoiRepository>> {

        return Observable.create { emitter: ObservableEmitter<List<PoiRepository>> ->

            val observableProducer = database.collection(KEY_POIS)
                    .addSnapshotListener(EventListener<QuerySnapshot> { querySnapshot, e ->

                        // Check to see if an error occurred.
                        if (e != null) {
                            emitter.onError(e)
                            return@EventListener
                        }
                        if (!querySnapshot!!.isEmpty) {
                            val results = mutableListOf<PoiRepository>()
                            for (document in querySnapshot.documents) {
                                val sentPOI = document.toObject(FireStorePoiResponse::class.java)
                                results.add(sentPOI!!.mapToRepository())
                            }

                            emitter.onNext(results)
                        } else {
                            Log.d(TAG, " QuerySnapshot is empty")
                        }
                    })
            emitter.setCancellable { observableProducer.remove() }
        }
    }

But for the life of me I cannot get your library to work. Can someone share an example of using the library to fetch a collection of objects from Firestore?

Firebase Storage: cancel a task / download

As you probably know, method getFile() in Firebase Storage returns StorageTask<FileDownloadTask.TaskSnapshot> which extends from CancellableTask. Both classes are cancellable, which means we could cancel the current download.

More info here.

Sample code:

StorageTask fileDownloadTask = someFileStorageRef.getFile(someFile).addOnSuccessListener(taskSnapshot -> {
                doStuff();
              });

// Somewhere in your project a user wants to cancel this download.
fileDownloadTask.cancel();

This feature would be quite interesting in order to let a user cancel the download.

Firestore ObserveCollection

Hi,

Are there plans to add a way to observe a snapshot of a query rather than just using .get()?

Basically looking for support for this:

Query firestoreQueryRef = firestore.collection("users") firestoreQueryRef.addSnapshotListener(..)

Thanks for all the good work!

ValueEventListener not removed.

  • If i create a disposable like this and dispose it later in onStop, disposable gets disposed but valueEventListener continues to listen.
private Disposable readNotification;
 readNotification = RxFirebaseDatabase.observeValueEvent(databaseRef), DataSnapshotMapper.listOf(Notification.class))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(notification ->
                        {
                       //something here;
                        }          
                );
readNotification.dispose();

add javadoc

Some form of javadoc would be nice, because it's not everytime clear, which method will be best.

RxFirestore getDocument() exists

The RXFirestore getDocument() method currently returns a Maybe, but onSuccess is only called if the document exists.

I need this document to be returned regardless of whether it exists or not, as if it doesn't I need to create the document, but if it does I need to update it.

Hope this makes sense?

Add License

So we can mention it in the app's licenses page.

Question

Hi, i am having difficulty when querying multiple tables and listening for changes.
Table1 is:

user_id: {
    roomId1:true,
    roomId2:true
}

and Table2 is:

roomId1:{},
roomId2{},

I have to query table1 first and get roomIDs of user. Then get details of each room from table2. Then listen for changes of table1 (if table1 changes, i have to requery table2).

Initially i have used RxFirebaseQuery but it does not listen for changes.

Problem after upgrading gradle to 3.0.0-alpha1 and changing maven address

Error:Could not find com.github.frangsierra:rx2firebase:1.1.1.
Searched in the following locations:
file:/C:/Android/sdk/extras/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
file:/C:/Android/sdk/extras/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
file:/C:/Android/sdk/extras/google/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
file:/C:/Android/sdk/extras/google/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
file:/C:/Android/sdk/extras/android/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
file:/C:/Android/sdk/extras/android/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
file:/C:/Android/Android Studio/gradle/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
file:/C:/Android/Android Studio/gradle/m2repository/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
https://jcenter.bintray.com/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
https://jcenter.bintray.com/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
https://maven.google.com/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.pom
https://maven.google.com/com/github/frangsierra/rx2firebase/1.1.1/rx2firebase-1.1.1.jar
Required by:
project :app

It happened after changing maven address to 'https://maven.google.com' and upgrading gradle version to 3.0.0-alpha1

Production error using Rx2Firebase

Hi @FrangSierra, I have plenty of users hitting non-fatal exceptions pointing to:

Non-fatal Exception: durdinapps.rxfirebase2.exceptions.RxFirebaseDataException
       at durdinapps.rxfirebase2.RxFirebaseDatabase$3$1.onComplete(RxFirebaseDatabase.java:130)
       at com.google.android.gms.internal.zzeck.run(Unknown Source)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:145)
       at android.app.ActivityThread.main(ActivityThread.java:7007)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

As per the decompiled class, the error happens on public static Completable setValue(@NonNull final DatabaseReference ref, final Object value), but that method doesn't seems to be using any RxFirebaseDataException instance. I can't seem to find any logic nor explanation to why this might be happening 😕 . I'm a little bit puzzled with this, so any help you might be able to provide will be awesome!

Thanks man!

Error when trying to set data in firestore using HashMap

FATAL EXCEPTION: main
Process: com.pocktor.android.dev, PID: 29855
java.lang.NoSuchMethodError: No virtual method set(Ljava/util/Map;Lcom/google/firebase/firestore/SetOptions;)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/firestore/DocumentReference; or its super classes (declaration of 'com.google.firebase.firestore.DocumentReference' appears in /data/app/com.pocktor.android.dev-O96hCBhCneUJXu3Wl598Rg==/split_lib_dependencies_apk.apk!classes2.dex)
at durdinapps.rxfirebase2.RxFirestore$11.subscribe(RxFirestore.java:361)
at io.reactivex.internal.operators.completable.CompletableCreate.subscribeActual(CompletableCreate.java:39)
at io.reactivex.Completable.subscribe(Completable.java:2302)
at io.reactivex.internal.operators.maybe.MaybeFlatMapCompletable$FlatMapCompletableObserver.onSuccess(MaybeFlatMapCompletable.java:91)
at io.reactivex.internal.operators.maybe.MaybePeek$MaybePeekObserver.onSuccess(MaybePeek.java:122)
at io.reactivex.internal.operators.maybe.MaybeCreate$Emitter.onSuccess(MaybeCreate.java:73)
at durdinapps.rxfirebase2.RxHandler.onSuccess(RxHandler.java:36)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Please update the firestore gradle version. I think that will solve this issue.

Firestore : Crash when permission denied (null value in Rx chain)

Hi @FrangSierra,

Thanks again for your library.

I found a unwanted behavior when I get an PERMISSION_DENIED from firestore: my app crash.

When Firestore return this error, the OnCompleteListener is called, not the failure. But, the result is empty (null) and the rx chain is broken due to this null value (and my app crash).

A screenshot of the problem :
screenshot

I think a acceptable approach would be to check the null value before emitting the onSuccess(). If a null is found, call onError with a typed exception like FirestorePermissionDeniedException (or just return the original exception which is typed).

Thanks a lot!

Changed behaviour for RxFirebaseDatabase.observeValueEvent

Hi,

Last version added check datasnapshot.exists() in the above method. As long as adding that in observeSingleValueEvent makes sense (probably everyone using lib were filtering on it anyway), adding this in observeValueEvent changes behaviour significantly.

There is no way to know now if the passed DatabaseReference exists or not (to act accordingly).
IMO it should be left to the lib user to deal with that (maybe warn in java doc).

Cheers,
Greg.

feature request: more info on cast exceptions

Sometimes i'm getting the following exception:

Fatal Exception: java.lang.Throwable
Can't convert object of type java.lang.Long to type models.f
durdinapps.rxfirebase2.DataSnapshotMapper.getDataSnapshotTypedValue (DataSnapshotMapper.java:47)

Though I understand what this means, I can understand why. This seems completely ramdon. I was wondering id we could get some extra info in the exception. Maybe something like this:

private static <U> U getDataSnapshotTypedValue(DataSnapshot dataSnapshot, Class<U> clazz) {
    U value = null;
    try{
         value = dataSnapshot.getValue(clazz);
    }catc(Exception ex){
        throw Exceptions.propagate(new RxFirebaseDataCastException(
            "unable to cast firebase  data response " + dataSnapshot.toString() + " to " + clazz.getSimpleName()));
    }
    if(value == null){
        throw Exceptions.propagate(new RxFirebaseDataCastException(
            "unable to cast firebase  data response " + dataSnapshot.toString() + " to " + clazz.getSimpleName()));
    }
    
    return value;
}

How to use with concat operator? (Suggest : Add an Example)

I'm trying to check two url's, so I need to combine them with concat operator, see below code:

String publicFolderRef = USER_STORAGE_REF + user.getUid() + "/public/" + PUBLIC_KEY;
    StorageReference refpub = storageRef.child(publicFolderRef);
    Maybe<Uri> obs1 = RxFirebaseStorage.getDownloadUrl(refpub);

    String privateFolderRef = USER_STORAGE_REF + user.getUid() + "/" + PRIVATE_KEY;
    StorageReference refPriv = storageRef.child(privateFolderRef);
    Maybe<Uri> obs2 = RxFirebaseStorage.getDownloadUrl(refPriv);

    Maybe.concat(obs1, obs2)
        .subscribeOn(Schedulers.io())
        .subscribe(new Subscriber<Uri>() {
          @Override public void onSubscribe(Subscription s) {

          }

          @Override public void onNext(Uri uri) {

          }

          @Override public void onError(Throwable t) {
            listener.onFailed(t.getMessage());
            Timber.e("onError(): "+t.getMessage());
          }

          @Override public void onComplete() {
            listener.onSuccess();
          }
        });

But I get nothing :(,
is it not supported concat operators ?
Thanks

Flowable not working on proper scheduler?

Hi.
I'm trying to use RxFirebaseDatabase with LiveData, so I made a following code:

package pl.karol.common

import android.arch.lifecycle.LiveData
import android.util.Log
import com.google.firebase.database.FirebaseDatabase
import durdinapps.rxfirebase2.RxFirebaseDatabase
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import pl.karol.common.data.Employee

class EmployeesLiveData : LiveData<List<Employee>>() {

    private val mQuery = FirebaseDatabase.getInstance().getReference("/employees")

    private var mDisposable: Disposable? = null

    override fun onActive() {
        super.onActive()
        mDisposable = RxFirebaseDatabase.observeValueEvent(mQuery)
                .map {
                    Log.d(TAG, "onActive: " + Thread.currentThread().name)
                    it.children
                            .mapNotNull {
                                val emp = it.getValue(Employee::class.java)
                                emp?.id = it.key
                                emp
                            }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    value = it
                }
    }

    override fun onInactive() {
        mDisposable?.dispose()
        mDisposable = null
        super.onInactive()
    }

    companion object {
        private const val TAG = "EmployeesLiveData"
    }
}

As far as I understand Rx the log message should come from Io thread. However what I see in logcat is:

03-01 23:15:11.931 31649-31649/pl.karol.promel D/EmployeesLiveData: onActive: main

Did I misunderstand something? To fix this I have to do:

mDisposable = RxFirebaseDatabase.observeValueEvent(mQuery)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map {
                    Log.d(TAG, "onActive: " + Thread.currentThread().name)
                    it.children
                            .mapNotNull {
                                val emp = it.getValue(Employee::class.java)
                                emp?.id = it.key
                                emp
                            }
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    value = it
                }

RxFirebaseDatabase.observeValueEvent Crashes

RxFirebaseDatabase.observeValueEvent throws an error when the user signs out from Firebase.

io.reactivex.exceptions.UndeliverableException: RxFirebaseDataException{error=DatabaseError: This client does not have permission to perform this operation}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.