Introduction to Reactive Programming – DZone Java | xxxIntroduction to Reactive Programming – DZone Java – xxx
菜单

Introduction to Reactive Programming – DZone Java

二月 29, 2020 - MorningStar

Over a million developers have joined DZone.

  • Introduction to Reactive Programming - DZone Java

    {{node.title}}

    {{node.type}} · {{ node.urlSource.name }} by

    Download {{node.downloads}}

  • {{totalResults}} search results

{{announcement.body}}

{{announcement.title}}

Let’s be friends:

1024)” dc-slot=”ads.sl1.slot(articles[0], 0)” tags=”ads.sl1.tags(articles[0], 0)” size=”ads.sl1.size(articles[0], 0)” style=”border:0px;”>
1 && !articles[0].partner.isSponsoringArticle && (width > 1024)” dc-slot=”ads.sb2.slot(articles[0], 0)” tags=”ads.sb2.tags(articles[0], 0)” size=”ads.sb2.size(articles[0], 0)”>

Introduction to Reactive Programming

DZone ‘s Guide to

Introduction to Reactive Programming

This introduction to Reactive programming discusses the observable and oberserver model, as well as the operators and an example.

Apr. 08, 20 · Java Zone ·

Free Resource

Join the DZone community and get the full member experience.

Join For Free

Reactive programming is about dealing with data streams and the propagation of change.

Reactive systems are applications whose architectural approach make them responsive, resilient, elastic and message-driven.

  • Responsive: Systems should respond in a timely manner.
  • Message Driven: Systems should use asynchronous message communication between components to ensure loose coupling.
  • Elastic: Systems should stay responsive under high load.
  • Resilient: Systems should stay responsive when some components fail.

Introduction to Reactive Programming - DZone Java

Reactive systems

According to the “Reactive Manifesto”:

“Reactive Systems are more flexible, loosely-coupled and scalable. This makes them easier to develop and amenable to change. They are significantly more tolerant of failure and when failure does occur they meet it with elegance rather than disaster. Reactive Systems are highly responsive, giving users effective interactive feedback.”

There are Reactive libraries available for many programming languages that enable this programming paradigm.

Such libraries from the “ReactiveX” family are:

“..used for composing asynchronous and event-based programs by using observable sequences. It extends the observer patternto support sequences of data or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.” 

(definition by ReativeX)

So, it’s possible to avoid the “callback hell” problem and abstract other issues concerning threads and low-level asynchronous computations. That makes our code more readable and focused in business logic.

The Observable x Observer Model

Simply put, an observable is any object that emits (stream of) events, that the observer reacts to. The Observer Object subscribes to an Observable to listen whatever items the observable emits, so it gets notified when the observable state changes. The observer is also called subscriber or reactor, depending on the library used.

Introduction to Reactive Programming - DZone Java

Observable and observer

The Observer stands ready to react appropriately when the Observable emits items in any point in time. This pattern facilitates concurrent operations because it doesn’t need to block while waiting for the Observable to emit items.

The Observer contract expects the implementation of some subset of the following methods:

  •  OnNext: Whenever the Observable emits an event, this method is called on our Observer, which takes as parameter the object emitted so we can perform some action on it.
  •  OnCompleted: This method is called after the last call of the onNext method, indicating that the sequence of events associated with an Observable is complete and it has not encountered any errors.
  •  OnError: This method is called when it has encountered some error to generate the expected data, like an unhandled exception.

Operators

Operator is a function that, for every element the source Observable emits, it applies that function to that item, and then emit the resulting element in another Observable.

So, operators operate on an Observable and return another Observable. This way, operators can be combined one after other in a chain to create data flows operations on the events.

The behavior of each operator is usually illustrated in marble diagrams like this (Rx Marbles):

Introduction to Reactive Programming - DZone Java

Behavior of components

Reactive operators have many similarities to those of functional programming, bringing better (and faster) understanding of them.

Some of the most used core operators in ReactiveX libraries are:

  •  map : transforms items emitted by an Observable by applying a function to each them.
  • flatMap : transforms the objects emitted by an Observable into Observables (“nested Observables”), then flatten the emissions from those into a single Observable.
  • filter : emits only items from an Observable that pass a predicate test.
  • just : converts objects into an Observable that emits those objects.
  • takeWhile : discards items emitted by an Observable after a specified condition becomes false.
  • distinct : suppresses duplicate objects emitted by an Observable.

There is also an important concept of backpressure, which provides solutions when an  Observable  is emitting items more quickly than a  Observer  can consume them.


“Show Me the Code!"

After some background theory, let’s get to the fun part!

Below let’s go through a hands-on approach, to provide an understanding by seeing the magic in motion! 

The examples use the RxJava (version 1.3.8) library:

Java

 

x
 

1

<!-- maven dependency -->

2

<dependency>

3

   <groupId>io.reactivex</groupId>

4

   <artifactId>rxjava</artifactId>

5

   <version>1.3.8</version>

6

</dependency>

Here it is a simple inline “Hello World” code using an observable and immediate subscription:

Java

 

x
 

1

// simplest way (in-line)

2

public static void helloWorld1() {

3

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

4

}

It’s possible to do implicit or more explicit calls to observer functions/methods:

Java

 

<dependency>

0

1

14

 

1

<dependency>

1

2

<dependency>

2

3

<dependency>

3

4

<dependency>

4

5

<dependency>

5

6

<dependency>

6

7

<dependency>

7

8

<dependency>

8

9

<dependency>

9

10

   <groupId>io.reactivex</groupId>

0

11

   <groupId>io.reactivex</groupId>

1

12

   <groupId>io.reactivex</groupId>

2

13

   <groupId>io.reactivex</groupId>

3

14

   <groupId>io.reactivex</groupId>

4

Segregating Observable and Observer objects:

Java

 

   <groupId>io.reactivex</groupId>

5

1

16

 

1

   <groupId>io.reactivex</groupId>

6

2

   <groupId>io.reactivex</groupId>

7

3

   <groupId>io.reactivex</groupId>

8

4

   <groupId>io.reactivex</groupId>

9

5

   <artifactId>rxjava</artifactId>

0

6

   <artifactId>rxjava</artifactId>

1

7

   <artifactId>rxjava</artifactId>

2

8

   <artifactId>rxjava</artifactId>

3

9

   <artifactId>rxjava</artifactId>

4

10

   <artifactId>rxjava</artifactId>

5

11

   <artifactId>rxjava</artifactId>

6

12

   <artifactId>rxjava</artifactId>

7

13

   <artifactId>rxjava</artifactId>

8

14

   <artifactId>rxjava</artifactId>

9

15

   <version>1.3.8</version>

0

16

   <version>1.3.8</version>

1

The code above prints:

Java

 

   <version>1.3.8</version>

2

1

 

1

   <version>1.3.8</version>

3

2

   <version>1.3.8</version>

4

Since it is emitted just one item, it can be a single object:

Java

 

   <version>1.3.8</version>

5

1

 

1

   <version>1.3.8</version>

6

2

   <version>1.3.8</version>

7

3

   <version>1.3.8</version>

8

4

   <version>1.3.8</version>

9

5

</dependency>

0

Operators examples:

Java

 

</dependency>

1

1

12

 

1

</dependency>

2

2

</dependency>

3

3

</dependency>

4

4

</dependency>

5

5

</dependency>

6

6

</dependency>

7

7

</dependency>

8

8

</dependency>

9

9

// simplest way (in-line)

0

10

// simplest way (in-line)

1

11

// simplest way (in-line)

2

12

// simplest way (in-line)

3

The output of the code above is:

Plain Text

 

// simplest way (in-line)

4

1

 

1

// simplest way (in-line)

5

2

// simplest way (in-line)

6

3

// simplest way (in-line)

7

4

// simplest way (in-line)

8

5

// simplest way (in-line)

9

Interval operator:
Java

 

public static void helloWorld1() {

0

1

 

1

public static void helloWorld1() {

1

2

public static void helloWorld1() {

2

3

public static void helloWorld1() {

3

4

public static void helloWorld1() {

4

5

public static void helloWorld1() {

5

6

public static void helloWorld1() {

6

7

public static void helloWorld1() {

7

It’s also possible to get an Observable from a  List , a  Callable  or a  Future  instance:

Java

 

public static void helloWorld1() {

8

1

19

 

1

public static void helloWorld1() {

9

2

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

0

3

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

1

4

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

2

5

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

3

6

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

4

7

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

5

8

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

6

9

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

7

10

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

8

11

  Observable.just("Hello Reactive World 1!").subscribe(System.out::println);

9

12

}

0

13

}

1

14

}

2

15

}

3

16

}

4

17

}

5

18

}

6

19

}

7

Of course, we can set  <nerd mode on> and implement a Star Wars battle using Reactive Programming (source code here):

Java

 

}

8

1

45

 

1

}

9

2

<dependency>

00

3

<dependency>

01

4

<dependency>

02

5

<dependency>

03

6

<dependency>

04

7

<dependency>

05

8

<dependency>

06

9

<dependency>

07

10

<dependency>

08

11

<dependency>

09

12

<dependency>

10

13

<dependency>

11

14

<dependency>

12

15

<dependency>

13

16

<dependency>

14

17

<dependency>

15

18

<dependency>

16

19

<dependency>

17

20

<dependency>

18

21

<dependency>

19

22

<dependency>

20

23

<dependency>

21

24

<dependency>

22

25

<dependency>

23

26

<dependency>

24

27

<dependency>

25

28

<dependency>

26

29

<dependency>

27

30

<dependency>

28

31

<dependency>

29

32

<dependency>

30

33

<dependency>

31

34

<dependency>

32

35

<dependency>

33

36

<dependency>

34

37

<dependency>

35

38

<dependency>

36

39

<dependency>

37

40

<dependency>

38

41

<dependency>

39

42

<dependency>

40

43

<dependency>

41

44

<dependency>

42

45

<dependency>

43

The output of the code above may be (troopers ID numbers are random):

Plain Text

 

<dependency>

44

1

 

1

<dependency>

45

2

<dependency>

46

3

<dependency>

47

4

<dependency>

48

5

<dependency>

49

6

<dependency>

50

7

<dependency>

51

8

<dependency>

52


Resources and Further Readings

Topics:
java ,reactive programming ,rxjava ,observer ,observable ,react

Published at DZone with permission of Tiago Albuquerque . See the original article here.

Opinions expressed by DZone contributors are their own.

Java Partner Resources

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.linkDescription }}

{{ parent.urlSource.name }}

by

CORE

· {{ parent.articleDate | date:’MMM. dd, yyyy’ }} {{ parent.linkDate | date:’MMM. dd, yyyy’ }}


Notice: Undefined variable: canUpdate in /var/www/html/wordpress/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 51