RxAndroid - BehaviorSubject不在onNext上发出

时间:2017-02-25 16:17:38

标签: java android mvvm rx-java

我正在尝试用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();
}

1 个答案:

答案 0 :(得分:3)

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