Search code examples
androidandroid-studiorx-android

RxAndroid `Observable...subscribe` highlighted in Android Studio


I'm using RxAndroid to marshal a string from a background thread into the main thread, and do something with that string on that main thread:

String stringFromDatabase = readFromDatabase();

Observable.just(stringFromDatabase)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<String>() {
        @Override
        public void accept(String string) throws Exception {
            webViewFragment.onInjectMessage(string, null);
        }
    });

Android Studio is highlighting the entire Observable.just... command chain in yellow, telling me that "The result of subscribe is not used", when I hover on it.

If I add .dispose() to the end of the chain, the highlighting disappears, but the webViewFragment.onInjectMessage(string, null); code is no longer executed.

I noticed that I can remove the highlighting by adding a @SuppressLint("CheckResult") annotation to the entire method.

Is this something like a warning which can be safely ignored, or am I creating some kind of a memory leak or other problem here? Is this a bad practice?


Solution

  • You have to dispose it to avoid memory leak. Try to dispose inside onDestroy

    Disposable disposable;
    
    String stringFromDatabase = readFromDatabase();
    disposable = Observable.just(stringFromDatabase)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String string) {
                    webViewFragment.onInjectMessage(string, null);
                }
            });
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    
        disposable.dispose();
    }