Of course this is not the case, but to a reactive newbie this is not so obvious. I developed a relatable analogy that helped me understand and explain what happens in a reactive chain of Observable operations. This is more or less how I think of Observable operations.
The onNext()
The Observable emits items. I like to think of emissions as "handing" items to an Observer by calling it's onNext() method, which accepts the item as an argument.But Observable operators (like map(), flatMap(), etc) create Observables that are both an Observable and Observer.
Here is a relatable example. Take a moving crew (portrayed by my artistically crafted stick figures) passing boxes. A chain of Observable operations is much like a mover handing a box up a chain. Each time the box is pushed to the next person, the onNext() is called on the next guy to pass it.
You could say that the mover on the left is the "source" Observable, since he is the originator creating the emissions. He calls the middle guy's onNext() method to pass the box to him. The second guy in turn immediately calls the third guy's onNext() method, and so on. The final onNext() call will be on the final Subscriber. But the point is the second and third mover are observing the mover on their left. A mover reacts to a box getting pushed to him by turning around and pushing it to the next mover.
Here is a more thorough example showing these three movers each doing something more specific and can be represented in code.
If we were to express these three movers as an Observable chain of operations, this is what it might look like.
Observable<Item>- mover1 = Observable.create(s -> { while (house.hasItems()) { s.onNext(house.getItem()); } }); Observable<Box>
mover2 = mover1.map(item -> putInBox(item)); Subscription mover3 = mover2.subscribe(box -> putInTruck(box));
We could also express this into a single chain of Observable operators without any intermediary variables.
Observable.create(s -> { while (house.hasItems()) { s.onNext(house.getItem()); } }).map(item -> putInBox(item)).subscribe(box -> putInTruck(box));
However, if there is a finite number of items in the house we need to implement onCompleted().
The onCompleted()
Observables can be infinite, which means they will never call onCompleted() and are expected to forever emit items. But in this example, it is unlikely there are infinite items in the house. When Mover 1 has removed all items from the house, he needs to tell Mover 2 they are done by calling his onCompleted() method. He will in turn tell Mover 3 and call his onCompleted() method. Mover 3 will then close the truck and shutdown. Each mover will clean up and leave in this process as well.We would code the onCompleted() like this.
Observable- <Item> mover1 = Observable.create(s -> { while (house.hasItems()) { s.onNext(house.getItem()); } s.onCompleted(); }); Observable<Item>
mover2 = mover1.map(item -> putInBox(item)); Subscription mover3 = mover2.subscribe(box -> putInTruck(box), () -> closeTruck());
We need to have mover1 call onCompleted() since we created that source Observable from scratch, and that way it will communicate up the chain its completion event. The map() operation on mover2 created an Observable that already implements a call to onCompleted(). It just needs that notification from mover1 which we implemented. Since mover3 is the final Subscriber, we overload another lambda specifying to close the truck when onCompleted() is called.
The onError()
Errors can obviously happen in any program, but the reactive approach handles them a bit differently. The exception is emitted up the chain so the Subscriber can decide how to handle it. Of course there are operators to intercept the exception, and perform policies like resume next or retry a specified number of times. But generally you should have the Subscriber handle exceptions in some way.In this case, the map() operation failed. Mover 2 accidentally broke the item while trying to put it in a box. He calls onError() on Mover 3 who happens to be the final Subscriber, and Mover 3 comes down with a broom to handle the error.
Coding-wise, we have to handle the source Observable and catch any errors to pass up the chain. The error in this example does not occur at the source however. It occurs in the middle of the chain in the map() operation, which already implements passing the error up the chain. We also overload the Subscriber with another lambda to handle the error.
Observable- <Item> mover1 = Observable.create(s -> { try { while (house.hasItems()) { s.onNext(house.getItem()); } s.onCompleted(); } catch (Exception e) { s.onError(e); } }); Observable
<Box> mover2 = mover1.map(item -> putInBox(item)); Subscription mover3 = mover2.subscribe(box -> putInTruck(box), () -> closeTruck(), e -> cleanupMess());
Cool Thomas! Love the animated pics! You could demo backpressure too where the guy in the truck says "2 more, pass it on" to the next guy. That way the movers are enabled to drive the full truck off and bring in another one without things piling up.
ReplyDeleteHaha! I was just thinking about showing other operators. The RxMarbles are great, but they are still abstract and this provides something more relatable. This post was pretty well-received on Twitter so I might invest some time in creating more "RxMover" animations.
DeleteGreat Article
DeleteIEEE final year projects on machine learning
JavaScript Training in Chennai
Final Year Project Centers in Chennai
JavaScript Training in Chennai
Great Article
DeleteIEEE final year projects on machine learning
JavaScript Training in Chennai
Final Year Project Centers in Chennai
JavaScript Training in Chennai
Cool Thomas! Love the animated pics! You could demo backpressure too where the guy in the truck says "2 more, pass it on" to the next guy. That way the movers are enabled to drive the full truck off and bring in another one without things piling up.
ReplyDeleteVery helpful. Can you show schedulers too please. For me thats the most complex ones to undsrstand::-)
ReplyDeleteAdding notification to be alerted
DeleteYeah I've been thinking about schedulers too. I have some ideas I'll need to sift through. I might create a dedicated blog for these models.
DeleteJust wrote an entry on schedulers. http://tomstechnicalblog.blogspot.com/2016/02/rxjava-understanding-observeon-and.html
DeleteThanks Thomas your examples are enlightening! Can't wait for other posts!
DeleteExcellent analogy. Thanks a ton Thomas
ReplyDeleteExtremely useful post, thank you very much for writing it!
ReplyDeleteVery descriptive post. My blessing with you :P
ReplyDeleteThanks!
ReplyDeletegeek squad appointment |
best buy geek squad appointment |
best buy appointment |
geek squad appointment scheduling |
best buy geek squad appointment schedule |
bestbuy.com-appointments |
What a nice diagram and explanation! It was really helpful for me to understand the most basic part of the RxJava. Thanks
ReplyDeleteGreat information, i was searching of this kind of information, thankyou very much for sharing with us. i also have some links to share mcafee.com/activate
ReplyDeleteI found this is an informative blog and also very useful and knowledgeable. I would like to thank you for the efforts you have made in writing this blog norton.com/setup
ReplyDeletewww.norton.com/setup
Commonly what happens is we attempt to print a report on our brother printers yet can't do it because of error that we are unconscious of and the screen shows "printer in error state". Even subsequent to giving it a shot various occasions we neglect to determine it.At such a period we get bothered with our printers and are totally disturbed at what to do next to make it work. It is extremely simple to set up for the individuals who know How to Fix brother Printer In Error State however on the off chance that you can't do it.
ReplyDeletehow do i fix printer in error state
Thank you for sharing this blog, It is an amazing blog, I am really impressed by your blog, It’s really useful
ReplyDeleteBuy Ambien Online
Order Ambien Online
Buy Ambien 10mg Online
xanax bars for sale
fastest Modafinil delivery
ativan 2mg buy online
ativan 1mg tablet buy online
This is an informative blog. Keep it up. I am looking forward to this kind of blog. Thanks for sharing it with us
ReplyDeletebuy modalert online
buy artvigil online
buy waklert online
buy modvigil online
Xmedia Solutions
ReplyDeleteXmedia Solution About us in usa
Xmedia Solution infrastructure in usa
Xmedia Solution Career in usa
Xmedia Solution Contact us in usa
Fantasy Power 11 if you have a good knowledge of Cricket you Can play daily online ,live cricket games,
ReplyDeletecricket online games, best cricket games, play cricket online, cricket game online at best cricket games app for android phones to win real
cash and amount to instant approve in your bank or Paytm wallet.
play cricket online
Sotophone brings on the magic of Symphony Atom II in their web portal. Just go to the website and watch.
ReplyDeleteThank you for providing this blog really appreciate the efforts you have taken into curating this article if you want you can check out data science course in bangalore they have a lot to offer with regards to data science in terms of training and live projects.
ReplyDeletespeak for you.
ReplyDeletecomprare patente di Guida
comprar carta de conducao
420Buds