如何在android mvvm中用版本库设计清除rxJava disposables?

问题描述 投票:0回答:1

我是MVVM的新手,想清除我的rxJava disposables,我看到一些答案说在ViewModel的onClear方法中清除它,但我如何在第一时间添加disposable?

/仓库代码

public class MyRepository {


    public MutableLiveData<String> deleteDraftById(int recordId {

    final MutableLiveData<String> result = new MutableLiveData<>();

    Completable deleteDraftById = completedDao.deleteDraftById(recordId);
    deleteDraftById.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new CompletableObserver() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onComplete() {
                    result.setValue("1");
                }

                @Override
                public void onError(Throwable e) {
                    result.setValue(e.getMessage());
                }
            });
    return result;
   }
}

/ViewModel

  public class MyViewModel extends AndroidViewModel {

    public MutableLiveData<String> deleteDraftById(int recordId){
    return myRepository.deleteDraftById(recordId);

    }
  }
android mvvm rx-java android-lifecycle
1个回答
0
投票

在我看来,在repos中使用实时数据并没有什么不妥,例如,如果需要单一的真实来源。下面是我的建议(rxjava 1.x假设,伪代码a-la java)。

public class MyRepository {
    public final MutableLiveData<String> result = new MutableLiveData<>();

    public Completable deleteDraftById(int recordId) {
        return completedDao.deleteDraftById(recordId)
            .doOnSubscribe(...) //potentially report progress start, if needed
            .doOnSuccess(...) //report success to your live data aka result.value = ...
            .onErrorComplete(...) //report error to your live data and complete
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    }
}
  public class MyViewModel(....pass MyRepository) extends AndroidViewModel {

    //expose live data from repo somehow, may be like this:
    public final LiveData<String> abc = myRepository.result;

    private final CompositeSubscription compositeSubscription = new CompositeSubscription();

    //call this from ui
    public void delete(int recordId) {
        compositeSubscription.add(
            myRepository
                .deleteDraftById(recordId)
                .subscribe()
        )
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        compositeSubscription.clear();
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.