简体   繁体   English

RxAndroid-BehaviorSubject在onNext上不发出

[英]RxAndroid - BehaviorSubject not emitting on onNext

I am trying to learn RXJava with MVVM pattern. 我正在尝试使用MVVM模式学习RXJava。

Here is scenario I am trying to implement: 这是我尝试实现的方案:

On some search event I am calling SearchViewModel.handleSearchTopic() which is emitting list but somehow it is not getting caught in observer's onNext event. 在某些搜索事件上,我正在调用SearchViewModel.handleSearchTopic(),该事件正在发出列表,但由于某种原因它没有被观察者的onNext事件捕获。 Subscription is also happening successfully. 订阅也成功进行。 I think I am doing some simple mistake, please point that. 我想我在犯一些简单的错误,请指出这一点。 Also, is there any better way of implementing this use case? 另外,有没有更好的方法来实现此用例?

SearchViewModel.java 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 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();
}

It was a stupid mistake. 这是一个愚蠢的错误。 I was using different instances of SearchViewModel in fragment and search event. 我在片段和搜索事件中使用SearchViewModel的不同实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM