Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why onCompleted is not called in this code?

Tags:

rx-java

I have this subject in the viewmodel:

private PublishSubject<String> articleSubject;

public Observable<Article> newArticleSubject() {
    articleSubject = PublishSubject.create();
    return articleSubject.flatMap(new Func1<String, Observable<Article>>() {         
        @Override
        public Observable<Article> call(String articleId) {
            return dataModel.getArticleById(articleId).subscribeOn(Schedulers.newThread());
        }
    });
}

I bind the view like this:

viewModel.newArticleSubject()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new ArticleSubscriber());

And this is my subscriber:

 private class ArticleSubscriber extends Subscriber<Article> {

        @Override
        public void onCompleted() {
            Log.d("test", "This is not ever printed");
        }

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

        @Override
        public void onNext(Article article) {
            //do stuff
        }
}

onCompleted is never called, but onError and onNext are. Why? Inside dataModel.getArticleById(articleId), subscriber.onCompleted(); is called.

like image 789
Héctor Avatar asked Oct 24 '16 16:10

Héctor


1 Answers

As one can conclude from the image available in PublishSubject the documentation:

enter image description here

PublishSubject as well as other *Subjects will live until somone calls onError or onCompleted. In fact they are no different in this matter from any other Observable.

The newArticleSubject creates new PublishSubject and flat maps every item emitted to a different observable. In case getArticleById ends with error the observable returned by flatMap ends too. However when getArticleById emits and completes normally flatMap will continue to wait for new items to be emitted by articleSubject. If you need to explicitely end articleSubject just call articleSubject.onCompleted()

like image 65
miensol Avatar answered Sep 29 '22 00:09

miensol