Reactive programming is a programming paradigm oriented around data flows and the propagation of change. It involves expressing static or dynamic data flows and automatically propagating changes through the flow. Reactive programming uses asynchronous data streams that can emit values, errors, or a completion signal. RxJava is a library that uses the observer pattern to support reactive programming. It defines Observables that emit events to Observers. Subjects in RxJava can act as both Observables and Observers, allowing values to be pushed to subscribers. RxJava provides operators like filter and distinct to transform streams of data.
1. Intro to RxJavaWhat is Reactive Programming?
Prepared By: awais.mazhar@mobilelive.ca
2. Hello!
I am Awais Mazhar
Today I’ll give some intro about
reactive programming and RxJava.
3. We will discuss about
+ Reactive Programming
+ Why Rx ?
+ When Rx ?
+ What is Observer pattern?
+ Brief intro to RxJava
+ Some code examples
4. Reactive Programming
A programming paradigm oriented around data flows and the propagation
of change. This means that it should be possible to express static or
dynamic data flows with ease in the programming languages used, and that
the underlying execution model will automatically propagate changes
through the data flow.
Reactive programming is programming with asynchronous data
streams.
A stream is a sequence of ongoing events ordered in time. It can emit three
different things: a value (of some type), an error, or a "completed" signal.
5. Why Rx ?
Rx is a powerful tool that enables the solution of problems in an elegant
declarative style, familiar to functional programmers. Rx has several
benefits:
+ Unitive
Queries in Rx are done in the same style as other libraries inspired by functional
programming, such as Java streams. In Rx, one can use functional style
transformations on event streams.
+ Declarative
Functional transformations are read in a declarative way.
6. Why Rx ?
+ Extensible
RxJava can be extended with custom operators. Although Java does not allow for
this to happen in an elegant way, RxJava offers all the extensibility one can find Rx
implementations in other languages.
+ Composable
Rx operators can be combined to produce more complicated operations.
+ Transformative
Rx operators can transform one type of data to another, reducing, mapping or
expanding streams as needed.
7. When Rx?
Rx is fit for composing and consuming sequences of events.
Should be used When:
+ UI events like mouse move, button click
+ Domain events like property changed, collection updated, "Order
Filled", "Registration accepted" etc.
+ Infrastructure events like from file watcher, system.
+ Integration events like a broadcast from a message bus or a push
event from WebSockets API or other low latency middleware.
+ Integration with a CEP engine like StreamInsight or StreamBase.
8. Observer pattern
The observer pattern is a software design pattern in which an object, called
the subject, maintains a list of its dependents, called observers, and notifies
them automatically of any state changes, usually by calling one of their
methods.
It is mainly used to implement distributed event handling systems, in "event
driven" software. Most modern languages such as Java and C# have built in
"event" constructs which implement the observer pattern components, for
easy programming and short code.
9. Observer pattern
The observer pattern can cause memory leaks, known as the lapsed
listener problem, because in basic implementation it requires both explicit
registration and explicit deregistration, as in the dispose pattern, because
the subject holds strong references to the observers, keeping them alive.
This can be prevented by the subject holding weak references to the
observers.
A UML diagram of the observer pattern is on next Slide.
10.
11. Observer pattern
- Java Example
Here is an example written
in Java that takes keyboard
input and treats each input
line as an event.
12. Observer pattern
- Java Example
When a string is supplied
from System.in, method is
called, in order to notify all
observers of the event's
occurrence.
14. RxJava
Rx is based around two fundamental types, while several others
expand the functionality around the core types. Those two core types
are the Observable and the Observer, which will be introduced in
coming slides. We will also introduce Subjects, which ease the learning
curve.
15. RxJava - Observable
This class contains a lot of the implementation of Rx, including all of the
core operators. Subscribe method is very important.
public final Subscription subscribe(Subscriber<? super T> subscriber)
This method is used to receive the values emitted by the observable.
Values are pushed to the subscriber, which is then responsible for the
behaviour intended by the consumer.
16. RxJava - Observable
An observable pushes 3 kinds of events.
+ Values
+ Completion, which indicates that no more values will be pushed.
+ Errors, if something caused the sequence to fail. These events also
imply termination.
17. RxJava - Observer
This interface has three methods, behaviour that is executed every
time the observable pushes a value. The observer will have its onNext
called zero or more times, optionally followed by an onCompleted or an
onError. No calls happen after a call to onError or onCompleted.
interface Observer<T> {
void onCompleted();
void onError(java.lang.Throwable e);
void onNext(T t);
}
18. RxJava - Observer
- Java Implementation
Here is an Observable which
is only pushing data one
time to it's all subscribers
(as OnNext() is called once).
And Subscriber is printing
whatever received.
19. RxJava - Subject
Subjects are an extension of the Observable that also implements the
Observer interface.They can have events pushed to them (like observers),
which they then push further to their own subscribers (like
observables).There are a few different implementations of Subject.
We will now examine the most important ones and their differences.
20. RxJava - Subject
- PublishSubject
When a value is pushed into
a PublishSubject, the
subject pushes it to every
subscriber that is
subscribed to it at that
moment.
21. RxJava - Subject
- ReplaySubject
When a new subscription is
made, the event sequence is
replayed from the start for the
new subscriber. After catching
up, every subscriber receives
new events as they come.
BehaviorSubject is same as this
but it only remember the last
value.
22. RxJava - Subject
- AsyncSubject
It also caches the last value.
The difference now is that it
doesn't emit anything until
the sequence completes. Its
use is to emit a single value
and immediately complete.
23. RxJava - Lifetime management
We have control over when to begin and stop accepting values.
Subscriptions may be linked to allocated resources that we will want to
release at the end of a sequence. Rx provides control over your
subscriptions to enable you to do that.
- Subscribing
There are several overloads to Observable.subscribe, which are shorthands for
the same thing.
Subscription subscribe() //Subscription subscribe(Subscriber<? super T> subscriber)
Subscription subscribe(Action1<? super T> onNext)
Subscription subscribe(Action1<? super T> onNext, Action1<java.lang.Throwable>
onError)
24. RxJava - Lifetime management
You can also stop receiving values before a sequence terminates. Every
subscribe overload returns an instance of Subscription, which is an
interface with 2 methods:
boolean isUnsubscribed()
void unsubscribe()
Calling unsubscribe will stop events from being pushed to your
observer.
25. RxJava -Life Mgt
- Unsubscribing
Here in this example, after
receiving two values we
unsubscribed our subscriber
and you can see output as
well.
26. RxJava - Observable Factory Methods
In previous examples we used Subjects and manually pushed values
into them to create a sequence. We used that sequence to
demonstrate some key concepts and the first and most important Rx
method, subscribe.
27. RxJava -Observable
- Observable.just
The just method creates an
Observable that will emit a
predefined sequence of
values, supplied on creation,
and then terminate.
29. RxJava -Observable
- Observable.create
It is basically a function that
takes a Subscriber<T> for
type T. Inside it we can
manually determine the
events that are pushed to
the subscriber.
30. RxJava -Observable
- Observable.range
It emits the specified range
of integers.
- Observable.Interval
It will create an infinite
sequence of ticks,
separated by the specified
time duration.
31. RxJava -Observer
- Filter
filter takes a predicate
function that makes a
boolean decision for each
value emitted. If the decision
is false, the item is omitted
from the filtered sequence.