Observable.map(w -> w.toUpperCase().hashCode()).subscribe(consumer) It is called transformation.Īs mentioned before, you can change the data type of the event as well in transformation process. So every word first goes through map() method and then goes to subscriber for further handling. In above example, we have added one intermediate method map() before subscribing the observable. Observable.map(w -> w.toUpperCase()).subscribe(consumer) It is a simple transformation, but you will get the concept. In our hello world example, we want to print the words in UPPERCASE. This is necessary to provide support for intermediate transformation of events between the source and target, so that both work the way they designed for and still they are compatible. They can be different in data it contain, the data types or any other major difference between received and emitted event. In RxJava, the event type which subscriber receive from observable and event type which subscriber emits, do not need to be same. When the observable finishes all of words either successful or with an error, the onComplete() or the onError() method is called on the subscriber. Internally in code, when a new word is emitted from the observable, the onNext() method is called on each subscriber. As soon as, we connect both, words/events start flowing and subscriber start printing them in console. Lastly, we connect the subscriber to consumer using subscribe(). This consumer is nothing but the subscriber. Then we create a consumer which can act on these words – in this case it is just printing them out to console. An observable is created for these events. In above example, "how", "to", "do", "in", "java" can be considered as stream of events. Observable observable = Observable.just("how", "to", "do", "in", "java") Let’s look at a very basic RxJava hello world example. Please note that an observable can have any number of subscribers. A callback is an approach to reactive programming done imperatively.įor example, if you have one source of data (producer) and one target for data (consumer) then after connecting the consumer to subscriber – reactive programming framework is responsible for pushing the data, generated by the producer, to the consumer. Reactive programming is a general programming term that is focused on reacting to changes, such as data values or events. What is RxJava and Reactive Programming 2. RxJava looks like Observer design pattern too – but with a difference – Observables often don’t start emitting items until someone explicitly subscribes to them. An Observable emits items a Subscriber consumes those items. The basic building blocks of reactive code are Observables and Subscribers. It is much closer to functional programming as seen in java 8 lambda expressions. RxJava 2.0 is open source extension to java for asynchronous programming by NetFlix.
0 Comments
Leave a Reply. |