在RxJava中实现自定义Subject <t,e =“”>

时间:2016-10-25 07:37:10

标签: rx-java

我有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

1 个答案:

答案 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();
}