如何使用存储库设计清除 android mvvm 中的 rxJava 一次性用品?

How to clear rxJava disposables in android mvvm with repository design?

我是 MVVM 的新手,正在尝试清除我的 rxJava 一次性用品,我看到一些答案说要在 onClear 方法的 ViewModel 中清除它,但是我如何首先添加一次性用品?

//存储库代码

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;
   }
}

//视图模型

  public class MyViewModel extends AndroidViewModel {

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

    }
  }

在我看来,在回购协议中使用实时数据并没有错,例如,如果需要单一事实来源。这是我的建议(假设 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();
    }
  }