如何将邮件传递给另一个订阅者?

时间:2017-12-22 06:07:06

标签: reactive-programming publish-subscribe java-9 reactive reactive-streams

我正在学习Java 9的Reactive Stream API。

由于它有发布者和订阅者,订阅者订阅了发布者,订阅者也实现了以下消息:

public class TestSubscriber<T> implements Subscriber<T> {

    @Override
    public void onComplete() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onError(Throwable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNext(T arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSubscribe(Subscription arg0) {
        // TODO Auto-generated method stub

    }

}

我没有在Subscriber中找到任何方法将消息传递给另一个订阅者。 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

这可以通过如下方式实现Flow.Processor来完成:

import java.util.concurrent.Flow;
import java.util.concurrent.Flow.Subscription;
import java.util.concurrent.SubmissionPublisher;
import java.util.function.Function;

public class MyTransformer<T, R> extends SubmissionPublisher<R> implements Flow.Processor<T, R> {

    private Function<T, R> function;
    private Flow.Subscription subscription;

    public MyTransformer(Function<T, R> function) {
        super();
        this.function = function;
    }

    @Override
    public void onComplete() {
        System.out.println("Transformer Completed");
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @Override
    public void onNext(T item) {
        System.out.println("Transformer Got : "+item);
        submit(function.apply(item));
        subscription.request(1);

    }

    @Override
    public void onSubscribe(Subscription subscription) {
        this.subscription = subscription;
        subscription.request(1);
    }


}

调用它时使用如下:

public class TestTransformer {

    public static void main(String... args) {
        SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
        MyTransformer<String, Integer> transformProcessor = new MyTransformer<>(Integer::parseInt);

        TestSubscriber<Integer> subscriber = new TestSubscriber<>();
        List<String> items = List.of("1", "2", "3");

        List<Integer> expectedResult = List.of(1, 2, 3);

        publisher.subscribe(transformProcessor);
        transformProcessor.subscribe(subscriber);
        items.forEach(publisher::submit);
        publisher.close();

    }
}