21 Kasım 2023 Salı

RxJava Observable.flatMapSequential metodu - Sonuç Sırasını Korur

Giriş
Açıklaması şöyle
This operator eagerly subscribes to its inner publishers like flatMap, but queues up elements from later inner publishers to match the actual natural ordering and thereby prevents interleaving like concatMap.
Örnek
Şöyle yaparız. Burada flatMapSequential ile çalıştırma paralel olsa bile çıktı sırası korunuyor
@Test void test_flatMap() { Flux.just(1, 2, 3) .flatMap(this::doSomethingAsync) //.flatMapSequential(this::doSomethingAsync) //.concatMap(this::doSomethingAsync) .doOnNext(n -> log.info("Done {}", n)) .blockLast(); } private Mono<Integer> doSomethingAsync(Integer number) { //add some delay for the second item... return number == 2 ? Mono.just(number).doOnNext(n -> log.info("Executing {}", n)) .delayElement(Duration.ofSeconds(1)) : Mono.just(number).doOnNext(n -> log.info("Executing {}", n)); }
Çıktı şöyle
// flatMap does not preserve original ordering, and has subscribed to all three elements // eagerly. Also, notice that element 3 has proceeded before element 2. 2022-04-22 19:38:49,164 INFO main - Executing 1 2022-04-22 19:38:49,168 INFO main - Done 1 2022-04-22 19:38:49,198 INFO main - Executing 2 2022-04-22 19:38:49,200 INFO main - Executing 3 2022-04-22 19:38:49,200 INFO main - Done 3 2022-04-22 19:38:50,200 INFO parallel-1 - Done 2 // flatMapSequential has subscribed to all three elements eagerly like flatMap // but preserves the order by queuing elements received out of order. 2022-04-22 19:53:40,229 INFO main - Executing 1 2022-04-22 19:53:40,232 INFO main - Done 1 2022-04-22 19:53:40,261 INFO main - Executing 2 2022-04-22 19:53:40,263 INFO main - Executing 3 2022-04-22 19:53:41,263 INFO parallel-1 - Done 2 2022-04-22 19:53:41,264 INFO parallel-1 - Done 3 //concatMap naturally preserves the same order as the source elements. 2022-04-22 19:59:31,817 INFO main - Executing 1 2022-04-22 19:59:31,820 INFO main - Done 1 2022-04-22 19:59:31,853 INFO main - Executing 2 2022-04-22 19:59:32,857 INFO parallel-1 - Done 2 2022-04-22 19:59:32,857 INFO parallel-1 - Executing 3 2022-04-22 19:59:32,857 INFO parallel-1 - Done 3










Hiç yorum yok:

Yorum Gönder