Asynchronous Programming in Java
Asynchronous Programming in Java
— T O QUIT OR NOT T O QUIT ? — T OP 50 S T ORIES WRIT ERS HERE ARE YOU CURIOUS ?
You have 2 free stories left this month. Sign up and get an extra one for free.
Here we will discuss the project Reactor using the spring web-Flux
module.
Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Flux
Flux can publish 0 or more values. It can of any type.
2. Flux.fromIterable()
This method is used when we have an instance of an iterable like list, set.
3. Flux.range()
This method is used to create a publisher of numbers.
4. Flux.empty()
This method is used to create an empty flux
5. Flux.error()
This method is used to publish some error response.
6. Flux.duration()
This method emits long values starting from 0 in the given duration
Flux.interval(Duration.ofMillis(1000));
These are the most commonly used flux creation methods. There are
few more like fromArray, fromStream, create, etc
Mono.empty()
Same as Flux this method is used to create empty Mono. Usually comes
when we don't want to return null, we can return empty Mono.
Mono.error()
It will publish an exception.
Mono.from()
This is used to create a new publisher from the existing one
Mono.justOrEmpty()
This method can take Optional value or direct value. In case of optional
value, it will return value if Optional is not null else only emit
onComplete In case of direct value it will return the value or emit
onComplete if null is passed
Mono<Object> justOrEmptyMono1 =
Mono.justOrEmpty(Optional.ofNullable(null));
Mono<Integer> justOrEmptyMono2 =
Mono.justOrEmpty(Optional.ofNullable(1));
Mono<Integer> justOrEmptyMono3 = Mono.justOrEmpty(1);
Mono<Object> justOrEmptyMono4 = Mono.justOrEmpty(null);
Subscribing publishers
A publisher can only publish value when someone subscribe to it. When
we subscribe to any publisher, we can get 1 of three results
i) response
ii) error
onNext()
onError()
onComplete()
onNext() method is called when any success response emits from the
publisher. The OnError() method is called when an error response emits
from the publisher. The onComplete() method gets called in the end
when there are no more values left to emit. Its a kind of indicator to tell
subscriber that subscription is completed.
flux.subscribe(
onNext(),
onError(),
onComplete()
);
OnError() and onComplete() are terminator methods means once they get
called, the subscription ends.
integerFlux.subscribe(
(x) -> System.out.println(x),
error -> System.out.println("Error : " + error),
() -> System.out.println("Subscription completed")
);
Flux<Object> primaryFlux =
Flux.just(1, 2, 3, 4, new Exception("Something went wrong"));
primaryFlux.subscribe(
(x) -> System.out.println(x),
error -> System.out.println("Error : " + error),
() -> System.out.println("Subscription completed")
);
In this example onNext() will get called 4 times and onError() will get
called once. Subscription got cancelled after onError() method so
onComplete() will not get called.
So from the above example, we can conclude that only one of onError()
and onComplete() can get called in any subscription.
Intermittent functions
These are the functions which take the values from the publisher and
perform some functions on it before passing it to a subscriber.
1. map
This method is used to transform the values from a publisher (Flux or
mono) before passing it to a subscriber.
fluxWithError.subscribe(
System.out::println,
error -> System.out.println("Error : " + error),
() -> System.out.println("Subscription completed")
);
// Output :
// 121
// 144
// 169
// 196
// Subscription completed
1. buffer
We can use it in 2 ways: 1st with buffer size and 2nd with time duration
In the case of buffer size, we can set the number of values that we want
to emit at 1 time.
integerFlux
.buffer(2)
.subscribe(x-> System.out.println(x)); // [[1, 2], [3, 4]]
integerFlux
.buffer(Duration.ofMillis(5000))
.subscribe(x-> System.out.println(x)); // [1,2,3,4]
It will emit all the values in 1 go because before 5000 ms it added all the
values in the buffer. Let say if we are getting 2 values in every 5000ms, So
the response will be like
2. doOnEach()
This method is used to check all the values of the publisher before
passing it to the subscriber
Flux.just(1,2,3,4)
.doOnEach(x -> System.out.println(x.get()))
.subscribe(x -> System.out.println("subscriber value" + x));
Output :
1
subscriber value1
2
subscriber value2
3
subscriber value3
4
subscriber value4
null // In case when OnComplete runs the value of x is 0
is printed when we did x.get()
with this method, we can check which all method will get called and how
many times
Flux.just(1,2,3,4)
.doOnEach(x -> System.out.println(x.getType()))
.subscribe(x -> System.out.println("subscriber value" + x));
output :
onNext
subscriber value1
onNext
subscriber value2
onNext
subscriber value3
onNext
subscriber value4
onComplete
3. log()
This method is used for the logging purpose
Flux.just(1,2,3,4)
.log()
.subscribe(x -> System.out.println("subscriber value" + x));
It will log all the methods called in the subscriber with the order in which
they get called.
4. delayElement()
This method is used to delay the emission of value from the publisher for
the given time
Flux.just(1,2,3,4)
.delayElements(Duration.ofMillis(5000))
.subscribe(x -> System.out.println("subscriber value" + x));
5. subscribeOn()
By default, the whole subscription process works in the main thread
which subscribes to the publisher. We can change that using
subscribeOn() method
Flux.just(1,2,3,4)
.subscribeOn(Schedulers.parallel())
.subscribe(x -> System.out.println("subscriber value" + x));
6. blockFirst()
This method subscribes to the flux and returns the first element or null if
no value is present. This is usually used for testing
Flux.range(1, 10)
.doOnCancel(cancelCount::incrementAndGet)
.blockFirst();
assertThat(cancelCount.get()).isEqualTo(1);
7. blockLast()
This method subscribes to the flux and returns the last element or null if
no value is present. This is also usually used for testing
Flux.range(1, 10)
.doOnCancel(cancelCount::incrementAndGet)
.blockFirst();
assertThat(cancelCount.get()).isEqualTo(10);
8. timeout()
Propagate a TimeoutException as soon as no item is emitted within the
given Duration from the previous emission (or the subscription for the
first item).
Flux.just(1,2,3,4)
.timeout(Duration.ofMillis(1000))
.subscribe(x -> System.out.println("subscriber value" + x));
9. bufferUntilChanged()
This method adds the values into the buffer until they are the same and
emits them when it receives some other value.
Flux.just(1,1,2,2,3,4)
.bufferUntilChanged()
.subscribe(x -> System.out.println("subscriber value" + x));
output :
subscriber value[1, 1]
subscriber value[2, 2]
subscriber value[3]
subscriber value[4]
10. cache
This method is used to cache the values emitted from the publisher. we
can pass the count as a parameter, how many last emitted values we
want to cache. So when any other subscriber subscribes to it, there won't
be any need to go to the publisher.
flux.subscribe(System.out::println);
flux.subscribe(System.out::println);
This method is useful when we have a publisher with infinite values. And
we want to keep track of at least a few previously emitted values as well.
There are many many more methods present in Flux and Mono. For
whole list, you can refer to
https://projectreactor.io/docs/core/release/api/reactor/core/publisher
/Flux.html
https://projectreactor.io/docs/core/release/api/reactor/core/publisher
/Mono.html
A newsletter that delivers The Startup's most popular stories to your inbox once a
month. Take a look
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more
information about our privacy practices.
66 claps
WRIT T EN BY
Fun with array rotations Create and Deploy an Sepia Development Log Build your First React
Sachin Malhotra in AWS Lambda Function #1 —Beautiful Single Page App
HackerNoon.com for Data Collection with Environments and Tom in T he Startup
the AWS CLI Better Movement
Conor Aspell in T he Startup Emmett Boudreau in Chi
Media