'Cleanest way to dispose of Single subscriptions
I'm using RxHttpClient to make requests and return Single using .firstOrError(). I then subscribe to it to get the result. In order to dispose of that subscription, I used a CompositeDisposable like in the example below.
Is there some other way to do this that doesn't require so much boilerplate? Do I need to do this at all in the current situation?
This code is in an API that needs to make a request to another API to validate some data.
single = httpClient.retrieve(HttpRequest.POST("/endpoint", request), ResultDto.class)
.firstOrError()
.subscribeOn(Schedulers.io())
CompositeDisposable cd = new CompositeDisposable();
Disposable d = single.subscribe(result -> {
// ...
cd.dispose();
}, error -> {
cd.dispose();
});
cd.add(d);
Solution 1:[1]
Pretty much all of this is necessary, assuming you don't actually create CompositeDisposable like that and then throw it away.
You can save cd.add(d); and perhaps Disposable d= with RxJava 3 if you supply cd as the third parameter to subscribe.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akarnokd |
