为什么在此代码中不调用onCompleted?

时间:2016-10-24 16:03:06

标签: rx-java

我在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());
        }
    });
}

我像这样绑定视图:

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

这是我的订阅者:

 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,但onErroronNext是。为什么?在dataModel.getArticleById(articleId)内,会调用subscriber.onCompleted();

1 个答案:

答案 0 :(得分:8)

正如人们可以从PublishSubject the documentation中提供的图像得出结论:

enter image description here

在pomone调用PublishSubject*Subjects之前,

onError以及其他onCompleted生效。事实上,他们在此问题与其他任何Observable没有什么不同。

newArticleSubject创建新的PublishSubject平面地图每个发布到不同可观察对象的项目。如果getArticleById以错误结束,则flatMap返回的observable也会结束。但是,当getArticleById正常发布并正常完成时flatMap将继续等待以便articleSubject发出新项目。如果您需要明确地结束articleSubject,请致电articleSubject.onCompleted()