RxAndroid `Observable…subscribe` highlighted in Android Studio

与世无争的帅哥 提交于 2020-01-16 06:06:10

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/59254710/rxandroid-observable-subscribe-highlighted-in-android-studio

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