You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
DavidMGross edited this page Jun 5, 2013
·
28 revisions
RxJava is an implementation of Reactive Extensions – a library for composing asynchronous and event-based programs that use observable sequences – for the Java VM.
It extends the observer pattern to support sequences of data/events and adds operators that compose sequences together declaratively while abstracting away low-level threading, synchronization, thread-safety, concurrent data structures, non-blocking IO, and other such concerns.
It supports Java 5 or higher and JVM based languages such as Groovy, Clojure, Scala and JRuby.
Callbacks offer a solution to the tendency to block on Future.get() by not allowing anything to block. They are naturally efficient because they execute when the response is ready.
RxJava offers efficient execution and composition by providing a collection of operators with which you can filter, select, transform, combine, and compose Observables.
The Observable class can be thought of as a “push” equivalent to Iterable, which is “pull.” With an Iterable, the consumer pulls values from the producer and the thread blocks until those values arrive. By contrast, with an Observable the producer pushes values to the consumer whenever values are available. This approach is more flexible, because values can arrive synchronously or asynchronously.
The Observable type adds two missing semantics to the Gang of Four’s Observer pattern, to match those that are available in the Iterable type:
the ability for the producer to signal to the consumer that there is no more data available
the ability for the producer to signal to the consumer that an error has occurred
With these additions, RxJava unifies the Iterable and Observable types. The only difference between them is the direction in which the data flows. This is very important because now any operation you can perform on an Iterable, you can also perform on an Observable. Here is an example:
/** * Asynchronously calls 'customObservableNonBlocking' and defines * a chain of operators to apply to the callback sequence.*/defsimpleComposition() {
// fetch an asynchronous Observable<String> // that emits 75 Strings of 'anotherValue_#'
customObservableNonBlocking()
// skip the first 10
.skip(10)
// take the next 5
.take(5)
// transform each String with the provided function
.map({ stringValue->return stringValue +"_transformed" })
// subscribe to the sequence and print each transformed String
.subscribe({ println"onNext => "+ it })
}
// output
onNext => anotherValue_10_transformed
onNext => anotherValue_11_transformed
onNext => anotherValue_12_transformed
onNext => anotherValue_13_transformed
onNext => anotherValue_14_transformed