I am trying to learn RXJava with MVVM pattern.
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. 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
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();
}
It was a stupid mistake. I was using different instances of SearchViewModel in fragment and search event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.