Search code examples
javarx-java

Remove multiple subscription and keep it to a single flow


I have the following method which works as expected.

But is there a way I could amend it so that I don't have to subscribe to the webclient's call separately

and instead let it be part of the flow and subscribe to it only once from some subscriber?

Note that this must ultimately return a Observable < Integer >.

Observable<Integer> observable = Observable.just(1)
        .delay(5, TimeUnit.MILLISECONDS)
        .compose(obs -> {
            webClient.putAbs("url")
                    .rxSend()
                    .doOnSubscribe(() -> System.out.println("Subbing to client")) // to be removed with solution
                    .subscribe(); // I don't want to have to do a sub here. 
            return obs;
        })
        .doOnSubscribe(() -> System.out.println("the only single sub i want to have"));

Some external subscriber would do the following.

observable.subscribe();

I would want this to trigger the overall flow which would also trigger the webclient's call instead of separately calling it as above.

Is this possible?

Thus looking for something like the following which doesn't subscribe to webClient separately.

Tried via flatmap and compose and not able to achieve it.

(The following is syntactically wrong. This is just to roughly show what I am looking for).

Observable<Integer> observable = Observable.just(1)
        .delay(5, TimeUnit.MILLISECONDS)
        .compose(obs -> webClient.putAbs(""))
        .rxSend()
        .toObservable();

Appreciate any guidance. Thanks.


Solution

  • This should work:

    Observable<Integer> observable = Observable.just(1)
                .delay(5, TimeUnit.MILLISECONDS)
                .flatMap(obs -> webClient.putAbs("url").rxSend().map(a -> obs));
    

    .flatMap() subscribes to the inner webClient call eagerly.