Convince Your Project Manager to use Reactive Extensions
Written by: Seyed Mohammad-Hossein Jafari
When I Started developing Android apps I was writing whatever came to my naïve mind. No matter I’m writing a 3 or 4 nested loops on the main thread or even getting all the tasks done in a single activity class. After a while I got into world of asynchronous task and concurrent jobs. I researched lots of options. From initializing a very simple thread to using a complex prewritten IntentService (a long-running thread class on android). The more I used Threads, the more concurrent problems I had to solve. There was time I found going single thread would have saved my time more than It worth going multithread!!!
Yet it was not the only problem. Finding the best algorithms and implementing best practices was always a thing for me. Every day I tried to do the best for that situation sometimes I failed, sometimes managed.
As I search the web for these needs and problems, a term always came up that I Didn’t know: Reactive Programming. And specially RxJava.
I’m not going to write another explanation or tutorial for RX because there are a ton out there that do the job a lot better than me. I this series of posts I would rather go through the advantages of using Reactive Extensions and how to pretty much persuade your project manager or your teammates and colleagues to start using it from very next project or even refactoring old codes to the Reactive ones!
One last thing to mention is that you could find all the references I have used (other than my own experience!) below.
Let’s start with a very simple example that can be done in an old fashion as well as Reactive approach programming.
asynchronous programming and in some term concurrency is a must and unavoidable these days. Going asynchronous has become so important that even some frameworks (Android, Silverlight) won’t allow you to perform certain tasks (ex: network) on their Main_Thread, thus writing async code and knowing how to implement it in an error-free style has become a compulsory requirement for every developer. every language provides its own way of using threads. Learning all the challenges and problems with multi-threading in general and specifically in that language is very hard and has a steep learning curve. therefore, frameworks usually come with their custom implementation to ease threading for a developer as much as they can (Ex: AsyncTask in Android). but there are times (quite often) that you need to implement your own way of threading. and doing so Is not as simple as it sounds. handling all the different situations, states and ways of not doing it wrong is time-consuming and boring plus it takes a lot of effort!
Here come the hero Reactive Extensions. Some smart and intelligent folks have implemented all these needs for you in package form called Schedulers. With a single call of subscribeOn in the middle of your chain, you can force the code to be run in the Thread that you like, you can even provide your own thread of desire to run on! Some of the out of the box available options are: IO (which can help you run your server request task as well as all the Input/output tasks on the specific thread that is designed to do so.), Computation (you need to map your objects or even some heavy work, use this schedule), Single (when wiring sequential code is a must for your case and use to get the same thread for your jobs) and many more. Android developer folks can use RXAndroid to be able to use main_thread as an option.
As you can see switching threads using RX is nothing to bother at all. You should only remember one thing that every time you call subscribe/observed there is the price that you have to pay (which differs platform to platform), just make sure it worth it.
with the Help of Distinct operator, you can easily avoid duplicate events and use toList gives you the ability to make a list of all the events that have been emitted.
Now we can even Filter the event(items) pass through the stream easily using an operator with the same name!: Filter.
Here in the first Observable, I have emitted Integers which are in a list one by one by using fromIterable(list). Right after that, there is a distinct operator which checks list items to be unique. And finally using Filter I managed to get Even numbers only.
In the second Observable, I have created a list of all the items that have been emitted.
The piece of cake huh?! There is the only gotcha about the toList operator and that is your emitter has to call onComplete in order for it to make a list of the items.
So far we have managed the two goals we were after and that was Threading and good algorithms with best practices. But that’s not all of it. Reactive Extensions has a lot more to offer. Here are a few more.
Buffering Like A breeze
once upon a time there was a button that had one job ‘Clicking’. after years of clicking, he wondered if could break the world record of clicks! There he began to click as fast as he could but every time it was only one click per try!!! one-day Buffer operator came along and said: “give me the time of the record and start to click when I reach the time I will tell you how fast you did it! after a few times of trying our button won the prize of the fastest button on earth with help of his beloved friend, Buffer!
So using buffer we can get a list of events with the size that we provide.
As a developer implementing search inefficient and power saving way is a bit of work. let’s describe a scene where there is the search box that you want to get the text from and query your backend for that particular content. the user starts typing “L”, “Le”, “Lemon”, “Lemon “and “Lemon Juice” that’s more than 8 requests for one sentence. it comes at the cost of too much internet use, not accurate response, flooding the server and bad user experience. for the sake of our problems, we can make use of Debounce or/and Throttle. so we can wait until the user finishes typing and then make only one request to do the search. problems solved!
Here if have used the throttle to control my search events. The only difference between the throttle and debounce is that debounce refreshes the timer whenever a new event has been emitted. But throttle only applies accepts events that are passed after the timer has reached zero.
Polling and repeated tasks with reactive extensions are as simple as calling the RepeatWhen and RetryWhen there is a phenomenal blog post from RI that explains the two and every detail of their differences. but to get the idea of how they work let’s say we should poll GPS location in every 10 seconds and send it to our server or save it in our DB for this matter we can use a RepeatWhen operator which does exactly the same job with applied conditions. so if we need a repeated task Repeat operator takes care of everything but in case you need a back off plan or delayed task you can use Retry and Delay operators respectively.
Getting to know Reactive Programming might be difficult but don’t worry about this and that. Start writing and thinking in reactive fashion today and tomorrow you will be an expert with no doubt. Best tool to get hang of Rx is Marble Diagrams. Start using them and get know them by heart. In the site below you can play with them using RX operators.
Hope it comes handy and persuades your project manager to make use of RXs.
It was my very first blog post so there is a lot to be improved for the next one, please let me know in comments. Your thoughts are highly appreciated.
Written by: Seyed Mohammad-Hossein Jafari