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.
As one can conclude from the image available in PublishSubject
the documentation:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With