Tuesday, June 27, 2017

Tip for writing RxJava code for beginners

Let's say you are using RxJava (or RxAndroid) and your goal is to write code which looks something like the foo method shown in the snippet below. Once you are experienced in writing functional code this appears trivial, however for programmers used to imperative programming style this can appear daunting.

Here is a step by step process which should hopefully make things simpler.

Step 1: Invoke the first method in the desired chain, and use the IDE to assign it's return value to a local variable. This way you can see the type of this expression.
Step 2: Use the local variable created in Step 1 to invoke the second method. If you are unsure about map vs flatMap, simply use map by default. Again, using the IDE assign the result to a local variable. In this new variable a Maybe is nested inside an Observable.

Step 3: This nesting is a hint to change map to a flatMap operation.

Step 4: Follow the above steps for the remaining method calls in the goal.

Step 5: Simply use the IDE to inline all the local variables to reach the goal.

No comments:

Post a Comment