问题描述
我今天已经升级到Android Studio 3.1,它似乎增加了一些棉绒检查.这些棉绒检查之一是针对一次未存储在变量中的RxJava2 subscribe()
调用.例如,从我的房间数据库中获取所有玩家的列表:
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:
像这样的一次性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
)没有此绒毛.
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
实例变量,然后将所有Disposables添加到CompositeDisposable中(使用RxKotlin,您可以将addTo(compositeDisposable)
附加到所有Disposables中).最后,完成实例后,调用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()
.
这将消除棉绒警告,并确保正确管理您的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()).
这篇关于未使用订阅结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!