<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=2258763691017137&amp;ev=PageView&amp;noscript=1">
Simplex Software

In a previous entry of the blog we have seen how to synchronize the result of running parallel processes with Akka. This was done using a message-driven approach. Now, we will see how this is done using an event-driven approach with RXJava without even writing extra code (without the need of creating a separate class).

The next following examples are written in Kotlin since now it’s Google’s preferred language for Android app development*.

Fetch data from the fastest source


fun getNotifications() : Maybe<list> {
   val cache : Maybe<list> = cacheRepository.getNotifications()
   val network : Single<list> = networkRepository.getNotifications()
   return Maybe.concat(cache,network.toMaybe()).firstElement()
}

In this example of a cache, we use the concat reactivex operator to join both observables together and we take the first element that emits. If the element comes from the cache, it won’t do the network call. Maybe it is used here because the data may not be available in the cache so in this case, the results are taken from the network.

Make a request depending on another request


fun getNotificationsForUser() : Single<list> {
   val user : Single = userRepository.getUser()
   return user.flatMap { user-> networkRepository.getNotifications(user.userId) }
}

In this other example, we use the flatMap reactivex operator to first extract the user and then we use it to get the notifications from the network repository. This method produces 2 network calls in series.

Make two requests in parallel and combine the results


fun getAllNotifications() : Single<list> {
   val source1 : Single<list> = twitterRepository.getNotifications()
   val source2 : Single<list> = facebookRepository.getNotifications()
   return Single.zip( source1, source2,
       BiFunction { twitterNotifications: List, facebookNotifications: List ->
           val allNotifications = ArrayList()
           allNotifications.addAll(twitterNotifications)
           allNotifications.addAll(facebookNotifications)
           allNotifications
       }
   )
}

In the last example, we have two (there can be more!) different sources of notifications. As this is just an example, we group first the twitter notifications and then the facebook notifications. With the zip RxJava operator we wait until both responses arrive and combine those into one list of notifications.

This was a small summary, based on my personal experience. I hope you find it useful, if you did (or not) leave us a comment or send us an email to hi@simplex.software.

More on Rxjava here.

 

References

*https://techcrunch.com/2019/05/07/kotlin-is-now-googles-preferred-language-for-android-app-development/

 

Follow Us

Subscribe To Our Blog

Let Us Know What You Thought about this Post.

Put your Comment Below.