我的BaseViewModel为:
public class BaseViewModel extends ViewModel {
private MutableLiveData<ApiError> apiError = new MutableLiveData<>();
private MutableLiveData<ApiProgress> apiProgress = new MutableLiveData<>();
private CompositeDisposable compositeDisposable = new CompositeDisposable();
// Emit "progress's start" on subscribe and "progress's end" on after success or error.
// Add this to the observable action sequence with ".compose(baseTransformer())" before subscribe.
<T> SingleTransformer<T, T> baseTransformer() {
return upstream -> upstream
.doOnSubscribe(disposable -> {
Log.d("dis", "doOnSubscribe : " + disposable + " " + disposable.isDisposed());
compositeDisposable.add(disposable);
apiProgress.setValue(ApiProgress.start());
})
.doOnDispose(() -> Log.d("dis", "I am disposed.."))
.doFinally(() -> apiProgress.setValue(ApiProgress.stop()))
.doOnError(err -> {
apiError.setValue(ApiError.create(err));
});
}
public LiveData<ApiError> getApiError() {
return apiError;
}
public LiveData<ApiProgress> getApiProgress() {
return apiProgress;
}
@Override
protected void onCleared() {
super.onCleared();
if (!compositeDisposable.isDisposed()) {
compositeDisposable.dispose();
Log.d("dis", "compositeDisposable disposed");
}
}
}
和一个LoginViewModel为:
public class LoginViewModel extends BaseViewModel {
Disposable disposable;
private AuthRepository authRepository;
private MutableLiveData<Login> loginData = new MutableLiveData<>();
public LoginViewModel() {
authRepository = new AuthRepository();
}
public LiveData<Login> getLoginData() {
return loginData;
}
public void login(String userName, String password) {
disposable = authRepository.login(userName, password)
.compose(baseTransformer())
.subscribe(login -> loginData.setValue(login), err -> {
});
}
@Override
protected void onCleared() {
super.onCleared();
Log.d("dis", "LoginViewModel : " + disposable + " " + disposable.isDisposed());
}
}
我想处理由subscription方法返回的可抛弃型,但是我想在转换函数中进行处理,因此,我不需要每次都做。
我在日志中得到以下输出:
D/dis: doOnSubscribe : null false
D/dis: compositeDisposable disposed
D/dis: LoginViewModel : 0 false
请帮助我理解:为什么即使在CompositeDisposable成功处置后仍无法处置一次性物品。
答案 0 :(得分:0)
我通过添加新方法实现了这一目标
<T> void consumeApi(Single<T> apiSingle, Consumer<T> consumer) {
compositeDisposable.add(apiSingle
.compose(baseTransformer())
.subscribe(accept(consumer))
);
}
在BaseViewModel中。现在我只需要打电话
consumeApi(
authRepository.login(userName, password),
login -> loginData.setValue(login)
);
在LoginViewModel中。