问题
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?
Model
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;
}
Activity
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));
回答1:
Why RX create several instance of my model? How can I use only ONE instance of it?
If you look carefully the object in the heapdump is LiveRemoteModel$2
which indicates it is an anonymous class within LiveRemoteModel
.
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.
来源:https://stackoverflow.com/questions/44002734/android-rxjava2-memory-performance