The Flux publisher

The Flux class represents a stream of values. This means that an instance of the Flux type can emit values, and a subscriber can receive them. This class contains a lot of functions that can be divided into two groups:

  • Static factories that allow us to create a new instance of the Flux type from different sources, such as callbacks or arrays.
  • Operators that allow us to process emitted values

The following example code shows how this works:

fun fluxTest() {
Flux.fromArray(arrayOf(1, 2, 3))
.map { it * it }
.subscribe { println(it) }
}

The fromArray function creates a new instance of the Flux type that emits values from passed arrays, one by one. The map method allows us to modify a value from the upstream, and the subscribe method is needed to pass an Observer that takes the resulting values.

The output of this example looks as follows:

 1
4
9

The Flux provides a lot of operators that can be used to process the emitted values. The following example code demonstrates this:

Flux.fromArray(arrayOf(1, 2, 3))
.filter { it % 2 == 1 }
.map { it * it }
.reduce { sum, item -> sum + item }
.subscribe { println(it) }

The .filter, .map, .reduce, and .subscribe operators are provided by the flux. We will look at each one of them in detail in just a bit. 

From the operator point of view, a stream is divided into upstream and downstream. An operator takes a value from the upstream, modifies it, and passes the result to the downstream. The following diagram shows how operators work:

From the map operator point of view, the values emitted from the filter function belong to the upstream, and  the items that are taken by reduce belong to the downstream.

The result of the preceding example looks as follows:

1
9

The output shows that after all of the transformations, an instance of the Flux class emits only two numbers.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.78.102