Posted on

Android Firebase RxJava


android firebase rxjava

Designed by Freepik

In my previous post we looked at how to make views independent by encapsulating Firebase networking in them. This led to higher abstraction in your activities/fragments. Although it has some flaws, let’s see if RxJava approach is better

RxJava Best Cases

ImageViews that load user images just from user ids and cache user image urls across all ImageView instances (static map) id great. This approach was described in this post

It’s perfect with ImageViews, because they have fixed size, so it doesn’t matter when you fetch and load an image. It won’t affect your UI because layout already has left room for this image

But with TextView, when you set size to wrap_content – asynchronous load of different TextView’s really messes up your UI

android firebase rxjava

Here all TextVIew’s are to wrap_content and one of them encapsulates Firebase fetching, so it sets text separetly from when right TextView does it. It this case it’s better to fetch all data at once. Let’s do it with RxJava, because otherwise it’s a nested callback hell

RxJava

If you’re not familiar with RxJava – then start with this post first, you really need to start with very simple stuff first, like iterating over lists, mapping stuff etc to get into this

Add those libraries to dependencies

I’m using this library as RxJava Firebase wrapper

Dependent Pairs

If you remember from the previous post, we had a comment and a user models. Comment has just a user id in it, so you have to fetch user separately, but display in one line in UI

Here’s the way you can fetch those with RxJava and setup UI only after fetching both of them

Here we first fetch comment, then user and wrap them in a Pair. Although when learning RxJava I recommend to convert lambdas to anonymous classes to see the input and return values. Otherwise you’re not likely to understand anything

Fetch Lists

Now I need to fetch all comments and for each comment there will be a user to fetch and as a result it will be a List<Pair<Comment, User>>

I spent a while with that RxJava Firebase library and couldn’t figure out the way around because of Maybe class. So I decided to create Flowable myself and not use the library

Although super confusing to read and understand, it does exactly what I intended to. Loot at the way I create Flowable, inside there’s a simple Firebase code and on fetching value I call FlowableEmitter#onNext

More Complex

Using this approach for fetching lists consisting of multiple Firebase nodes is very easy and you don’t have to deal with nested callback hell. So if you need to go into even more complex networking with more nodes to fetch synchronously – you can implement it easy

More about RxJava with Firebase in the following posts