订阅的结果没有被使用 [英] The result of subscribe is not used
问题描述
我今天已经升级到 Android Studio 3.1,这似乎增加了一些 lint 检查.这些 lint 检查之一是针对未存储在变量中的一次性 RxJava2 subscribe()
调用.例如,从我的 Room 数据库中获取所有玩家的列表:
I've upgraded to Android Studio 3.1 today, which seems to have added a few more lint checks. One of these lint checks is for one-shot RxJava2 subscribe()
calls that are not stored in a variable. For example, getting a list of all players from my Room database:
Single.just(db)
.subscribeOn(Schedulers.io())
.subscribe(db -> db.playerDao().getAll());
结果是一个大的黄色块和这个工具提示:
Results in a big yellow block and this tooltip:
subscribe
的结果没有被使用
像这样的一次性 Rx 调用的最佳实践是什么?我应该在完成时保留 Disposable
和 dispose()
吗?还是我应该只是 @SuppressLint
并继续?
What is the best practice for one-shot Rx calls like this? Should I keep hold of the Disposable
and dispose()
on complete? Or should I just @SuppressLint
and move on?
这似乎只影响 RxJava2 (io.reactivex
),RxJava (rx
) 没有这个 lint.
This only seems to affect RxJava2 (io.reactivex
), RxJava (rx
) does not have this lint.
推荐答案
IDE 不知道您的订阅在未处理时可能产生什么潜在影响,因此将其视为潜在的不安全.例如,您的 Single
可能包含网络调用,如果您的 Activity
在执行过程中被放弃,这可能会导致内存泄漏.
The IDE does not know what potential effects your subscription can have when it's not disposed, so it treats it as potentially unsafe. For example, your Single
may contain a network call, which could cause a memory leak if your Activity
is abandoned during its execution.
管理大量 Disposable
的便捷方法是使用 CompositeDisposable;只需在封闭类中创建一个新的 CompositeDisposable
实例变量,然后将所有 Disposable 添加到 CompositeDisposable(使用 RxKotlin,您可以将 addTo(compositeDisposable)
附加到所有 Disposable).最后,当您完成实例时,调用 compositeDisposable.dispose()
.
A convenient way to manage a large amount of Disposable
s is to use a CompositeDisposable; just create a new CompositeDisposable
instance variable in your enclosing class, then add all your Disposables to the CompositeDisposable (with RxKotlin you can just append addTo(compositeDisposable)
to all of your Disposables). Finally, when you're done with your instance, call compositeDisposable.dispose()
.
这将消除 lint 警告,并确保您的 Disposables
得到正确管理.
This will get rid of the lint warnings, and ensure your Disposables
are managed properly.
在这种情况下,代码看起来像:
In this case, the code would look like:
CompositeDisposable compositeDisposable = new CompositeDisposable();
Disposable disposable = Single.just(db)
.subscribeOn(Schedulers.io())
.subscribe(db -> db.get(1)));
compositeDisposable.add(disposable); //IDE is satisfied that the Disposable is being managed.
disposable.addTo(compositeDisposable); //Alternatively, use this RxKotlin extension function.
compositeDisposable.dispose(); //Placed wherever we'd like to dispose our Disposables (i.e. in onDestroy()).
这篇关于订阅的结果没有被使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!