Is RxJava a good fit for branching workflows?

主宰稳场 提交于 2019-12-02 03:25:09

The grouping observable is the right way to go AFAIK. Personally, if anything in your picture between "split by a type" and "merge everything", is async, doing this in RX definitely has a lot of advantages like retry logic, buffering, error handling, backpressure, etc.. If it's regular non-async code it's a personal preference I guess. You could do it using RX, but you can also do everything between "split by a type" and "merge everything" using regular synchronous code.

Whatever way you chose, splitting up the code to make it more readable is always a good idea so you can "read the flow" as easy as we can read the image you attached.

Just an idea for another approach which may work for you: Instead of grouping/toMap, you could multicast the source and handle the branches individually.

Example:

@Test
public void multicastingShare() {
    final Observable<Integer> sharedSource = Observable.range(1, 10)
            .doOnSubscribe(dummy -> System.out.println("subscribed"))
            .share();
    // split by some criteria
    final Observable<String> oddItems = sharedSource
            .filter(n -> n % 2 == 1)
            .map(odd -> "odd: " + odd)
            .doOnNext(System.out::println);
    final Observable<String> evenItems = sharedSource
            .filter(n -> n % 2 == 0)
            .map(even -> "even: " + even)
            .doOnNext(System.out::println);

    // recombine the individual streams at some point
    Observable.concat(oddItems, evenItems)
            .subscribe(result -> System.out.println("result: " + result));
}

This video may be be helpful (at least the first 15 min)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!