我有PublishSubject
收到String
并发出Article
s
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);
}
});
}
articleSubject.onNext("1234");
我想创建一个扩展ArticleSubject
的类Subject<String, Article>
来封装此行为。我试过这个:
public class ArticleSubject extends Subject<String, Article> {
private PublishSubject<String> subject;
protected ArticleSubject(OnSubscribe<Article> articleOnSubscribe, final IMainDataModel dataModel) {
super(articleOnSubscribe); //<---- ?????
this.subject = PublishSubject.create();
this.subject.flatMap(new Func1<String, Observable<Article>>() {
@Override
public Observable<Article> call(String s) {
return dataModel.getArticleById(s);
}
});
}
@Override
public boolean hasObservers() {
return subject.hasObservers();
}
@Override
public void onCompleted() {
subject.onCompleted();
}
@Override
public void onError(Throwable e) {
subject.onError(e);
}
@Override
public void onNext(String s) {
subject.onNext(s);
}
}
但是,如何处理构造函数中的OnSubscribe
?我是否必须保留订阅者和所有内容?有没有办法将其委托给PublishSubject
?
答案 0 :(得分:2)
我找到了一个通用解决方案:
public abstract class SubjectBinding<T, E> implements Observer<T> {
private PublishSubject<T> origin;
public SubjectBinding() {
this.origin = PublishSubject.create();
}
@Override
public void onCompleted() {
origin.onCompleted();
}
@Override
public void onError(Throwable e) {
origin.onError(e);
}
@Override
public void onNext(T t) {
origin.onNext(t);
}
public Observable<E> asObservable() {
return origin.flatMap(new Func1<T, Observable<E>>() {
@Override
public Observable<E> call(T t) {
return asObservable(t);
}
});
}
protected abstract Observable<E> asObservable(T t);
}
和
private class ArticleSubject extends SubjectBinding<String, Article> {
@Override
protected Observable<Article> asObservable(String s) {
return dataModel.getArticleById(s);
}
}
现在,我可以发送String
个值:
articleSubject.onNext("1234");
并发出Article
s:
public Observable<Article> newArticleSubject() {
return new ArticleSubject().asObservable();
}