Just for a wrap up.
We could buy more servers,
we could wait a minute longer
and in the end we end up with.
public interface Publisher<T> {
public void subscribe(Subscriber<? super T> s);
}
public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {
}
Mono<T>
Flux<T>
// Flux
Flux<String> f = Flux.just("a", "b", "c");
Flux<Integer> g = Flox.fromIterable(Arrays.asList(1, 2, 3));
//Mono
Mono<String> m = Mono.empty();
Mono<Integer> n = Mono.just(1);
Publisher<T> publisher = ...;
publisher.subscribe(t -> {...});
but what about
let us go through some of them
public final <V> Flux<V> map(Function<? super T,? extends V> mapper)
Flux<String> foo = Flux.just("1", "2", "3");
foo.map(Integer::valueOf)
.map(i -> i = i * 2)
.subscribe(i -> log.info("Mapped value: {}", i));
public final Flux<T> filter(Predicate<? super T> p)
Flux<Integer> foo = Flux.just(1, 2, 3, 4, 5, 6);
foo.filter(i -> i % 2 == 0)
.subscribe(i -> log.info("Even numbers: {}", i));
public static Flux<Long> interval(Duration period)
Flux<Integer> foo = Flux.interval(Duration.ofSeconds(2));
foo.subscribe(i -> log.info("Emitting every 2 seconds: {}", i));
public static <I> Flux<I> merge(Iterable<? extends Publisher<? extends I>> sources)
Flux<Integer> foo = Flux.range(1,10);
Flux<Integer> bar = Flux.range(2,10);
Flux<Integer> mergedFlux = Flux.merge(Arrays.asList(foo, bar));
mergedFlux.subscribe(i -> log.info("Merged: {}", i));
public static <TUPLE extends Tuple2,V> Flux<V> zip(Publisher<? extends Publisher<?>> sources,
Function<? super TUPLE,? extends V> combinator)
Flux<String> nameFlux = Flux.just("Krzysiek","Zenek","Witek");
Flux<String> lastNameFlux = Flux.just("Kowalski","Nowak","Brzeczyszczykiwicz");
Flux<String> positionFlux = Flux.just("CEO","CTO","COO");
Flux<Worker> zippedFlux = Flux.zip(nameFlux, lastNameFlux, positionFlux)
.flatMap(zipped ->
Flux.just(new Worker(
zipped.getT1(),
zipped.getT2(),
zipped.getT2()
)
)
);
zippedFlux.subscribe(worker -> log.info("Zipped worker: {}", worker));
do you know that the stream might be hot or cold?
It's like the difference between TV and Netflix.
private fun coldFlux(): Flux<String> {
return Flux.interval(Duration.ofSeconds(2)).map { i -> "Emitting $i" }
}
private fun hotFlux(): Flux<String> {
return coldFlux().publish().autoConnect();
}
@Test
fun run() {
val flux = hotFlux().take(10)
flux.subscribe { i -> println("First subscriber: $i") }
Thread.sleep(5000);
flux.subscribe { i -> println("Second subscriber: $i") }
flux.subscribe { i -> println("Third subscriber: $i") }
flux.subscribe { i -> println("Fourth subscriber: $i") }
flux.subscribe { i -> println("Fifth subscriber: $i") }
Thread.sleep(20000);
}
But there are some exceptions:
But there are some exceptions: