RxAndroid `Observable...subscribe` 在 Android Studio 中突出显示 [英] RxAndroid `Observable...subscribe` highlighted in Android Studio

查看:38
本文介绍了RxAndroid `Observable...subscribe` 在 Android Studio 中突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RxAndroid 将一个字符串从后台线程编组到主线程中,并在该主线程上对该字符串执行一些操作:

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 以黄色突出显示整个 Observable.just... 命令链,告诉我订阅的结果未使用",当我悬停时就可以了.

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.

如果我将 .dispose() 添加到链的末尾,突出显示消失,但 webViewFragment.onInjectMessage(string, null); 代码不再执行.

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

我注意到我可以通过向整个方法添加 @SuppressLint("CheckResult") 注释来删除突出显示.

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?

推荐答案

你必须处理它以避免内存泄漏.尝试在 onDestroy

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

这篇关于RxAndroid `Observable...subscribe` 在 Android Studio 中突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆