问题描述
我创建了一个Observable(RxJava2 + Volley),每5秒重复一次,
它可以工作,但是当我转储 Java堆(内存)时,我的 Model JAVA类的实例很多,并且每当Observable重复执行一次,它就会增加. br>为什么RX创建我的模型的几个实例?我怎么只能使用它的一个实例?
I created an Observable(RxJava2 + Volley) that repeat for each 5 seconds,
It works but when I Dump Java Heap(memory),there are many Instance of my Model JAVA class,and it will increase for each time that the Observable get repeating.
Why RX create several instance of my model? How can I use only ONE instance of it?
模型
public RequestFuture<String> getLiveRefreshFuture() {
RequestFuture<String> future = RequestFuture.newFuture();
VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST
, REFRESH_URL
, future
, future) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return getRefreshParams();
}
};
VolleySingleton.getInstance().addToRequestQueue(request);
return future;
}
活动
private final CompositeDisposable disposables = new CompositeDisposable();
final LiveRemoteModel model = DaggerLiveComponent.builder().build().getModel();
Observable<LiveResponse> observable = Observable
.interval(Constants.TOOLBAR_BADGES_REFRESH_DELAY, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.map(dummy -> model.getLiveRefreshFuture())
.map(RequestFuture::get)
.map(LiveResponse::new)
.observeOn(AndroidSchedulers.mainThread());
DisposableObserver<LiveResponse> disposableObserver =
new DisposableObserver<LiveResponse>() {
@Override
public void onNext(@NonNull LiveResponse liveResponse) {
setToolbarBadges(liveResponse.getToolbarBadges());
}
public void onError(@NonNull Throwable e) {
Log.e("RX", "onError: ", e);
}
@Override
public void onComplete() {
Log.d("RX", "onComplete: ");
}
};
disposables.add(observable.subscribeWith(disposableObserver));
推荐答案
如果仔细看,堆转储中的对象是LiveRemoteModel$2
,表明它是LiveRemoteModel
中的匿名类.
If you look carefully the object in the heapdump is LiveRemoteModel$2
which indicates it is an anonymous class within LiveRemoteModel
.
查看您的代码,这很可能是每次调用model.getLiveRefreshFuture()
时都会创建的VolleyStringRequest
对象.在RX管道中没有保留该对象的任何东西,因此Volley中一定有保留它的对象.
Looking at your code this is probably the VolleyStringRequest
object that gets created each time model.getLiveRefreshFuture()
is called. There is nothing retaining that object within the RX pipeline so there must be something within Volley retaining it.
这篇关于Android RXJava2内存性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!