Monads in Android

Veeresh Kalmath
Aug 27, 2017 · 2 min read

You might be wondering how Monads and Android are related. I am asserting that many of the android developers are already using it but are unaware of it. Most of the android developers at least heard of RxJava and related libraries which have Monads. Infact RxJava I think of as Monads on Steroids. If you have heard of Rx then you already know Monads. If you have used flatmap operator then you already understand the Monad. Even if you are not using RxJava and using Java 8 or Kotlin in android app development then you already know Monads. Completable Futures, Optionals, Try, Streams all these are Monads.

There are tons of articles explaining Monad online. Monads are programmable semicolons(metaphor for Composing) OR They are like Boxes(metaphor of Containment) OR Monads are like Elephants(metaphor for Chaining) OR Monads are Burritos(metaphor for wrapping). Here, I am not trying to add one more to the list.

I think Of Monad as nothing more than a design pattern which is helps in removing the complexity in the code.

What makes RxJava (a Monad) so useful in android?

As a android developer I think Observable<T> makes life easier in 3 ways. There may be many other. These are my personal favorites. RxJava Observables are Monads on Steroids.

  1. Chaining/Composing: Chaining an Observable is easier and linear both in semantics and syntax. Its like a Builder pattern syntactically and Observer pattern semantically. Try to compose multiple Callbacks, it can be done but maintenance of that code is nightmare over period of time. Try to reason the callback down the rabbit hole of callback hell. Example: make an REST API call take result of that make another REST API call if fails then make a default API call. Every developer might have seen this kind of control flow.
  2. Error handling: Rx lifts the Error as first-class citizens. How do we handle Checked Exceptions in java? Using try…catch blocks. What we do in catch blocks? If exception happens deep down the call back hell, Log the exception and forget it. Its difficult to traceback the flow and handle the exception. With Rx Observables the error is handled in onError() of the Observer even in case of any exception/error occurred in between an of the operators in call chain.
  3. Easier mental modeling of threading: Threading in Rx world is as simple as calling operators. subscribeOn() and observeOn() makes multi-threading a breeze.

This makes more sense when we see actual working code. Will explain the concrete example in next article till then good bye..

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade