我正在尝试使用MVVM模式学习RXJava。

这是我尝试实现的方案:

在某些搜索事件上,我正在调用SearchViewModel.handleSearchTopic(),该事件正在发出列表,但由于某种原因它没有被观察者的onNext事件捕获。订阅也成功进行。我想我在犯一些简单的错误,请指出。另外,有没有更好的方法来实现此用例?

SearchViewModel.java

private final BehaviorSubject<List<Topic>> topicList = BehaviorSubject.create();

public void handleSearchTopic() {
    List<Topic> list = //getsomehow;
    topicList.onNext(list);
}

public Observable<List<Topic>> getTopicListObservable() {
    return topicList.asObservable();
}

Fragment.java
@NonNull
private CompositeSubscription subscription;

@NonNull
private SearchViewModel searchViewModel;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    searchViewModel = new SearchViewModel();
    bind();
}

@Override
public void onDestroy() {
    unBind();
    super.onDestroy();
}

private void bind() {
    subscription = new CompositeSubscription();

    subscription.add(searchViewModel.getTopicListObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<Topic>>() {
                @Override
                public void onCompleted() {
                    //do something
                }

                @Override
                public void onError(Throwable e) {
                    //do something

                }

                @Override
                public void onNext(List<Topic> topics) {
                    //ideally this should be called when event is emitted but not getting called

                }
            }));

}

private void unBind() {
    subscription.unsubscribe();
}

最佳答案

这是一个愚蠢的错误。我在片段和搜索事件中使用SearchViewModel的不同实例。

10-06 06:52