Potential hazards of adding lots of Disposables to a CompositeDisposable

Viewed 473

When going through a lot of articles that talk about Android MVVM architectures with RxJava 2 (such as this article), you often see something that looks like the following:

class LobbyViewModel extends ViewModel {

... 

void loadCommonGreeting() {
    loadGreeting(loadCommonGreetingUseCase.execute());
}

void loadLobbyGreeting() {
    loadGreeting(loadLobbyGreetingUseCase.execute());
}

MutableLiveData<Response<String>> getResponse() {
    return response;
}

MutableLiveData<Boolean> getLoadingStatus() {
    return loadingStatus;
}

private void loadGreeting(Single<String> single) {
    disposables.add(single
            .subscribeOn(schedulersFacade.io())
            .observeOn(schedulersFacade.ui())
            .doOnSubscribe(s -> loadingStatus.setValue(true))
            .doAfterTerminate(() -> loadingStatus.setValue(false))
            .subscribe(
                    greeting -> response.setValue(Response.success(greeting)),
                    throwable -> response.setValue(Response.error(throwable))
            )
    );
}

When you look at the logic of the above, you see that every time the user triggers an action, (loadCommonGreeting()/loadLobbyGreeting()) a new disposable will be added to the CompositeDisposable variable disposables.

In this case it probably won't be a huge deal, but I can imagine that maybe in some other scenarios the number of Disposables linked to the CompositeDisposables could run up to the thousands or more.

Is this considered a good or safe practice?

1 Answers
Related