[英]How can I add in reactive Java a new Object to an existing stream?
Assuming I've already a reactive stream and now I wanna add one more object to this existing stream. 假设我已经有一个响应流,现在我想向此现有流添加一个对象。 How can I do this?
我怎样才能做到这一点?
This is the approach i found, is this the way to go? 这是我发现的方法 ,这是走的路吗?
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
/**
* Created by ton on 10/11/16.
*/
public class Example {
private List<FluxSink<String>> handlers = new ArrayList<>();
public Flux<String> getMessagesAsStream() {
Flux<String> result = Flux.create(sink -> {
handlers.add(sink);
sink.setCancellation(() -> handlers.remove(sink));
});
return result;
}
public void handleMessage(String message) {
handlers.forEach(han -> han.next(message));
}
public static void main(String[] args) {
Example example = new Example();
example.getMessagesAsStream().subscribe(req -> System.out.println("req = " + req));
example.getMessagesAsStream().subscribe(msg -> System.out.println(msg.toUpperCase()));
example.handleMessage("een");
example.handleMessage("twee");
example.handleMessage("drie");
}
}
Suppose this is your existing stream: 假设这是您现有的流:
Flux<Integer> existingStream = Flux.just(1, 2, 3, 4);
You can concatenate two streams: 您可以连接两个流:
Flux<Integer> appendObjectToStream = Flux.concat(existingStream, Flux.just(5));
This will produce [1, 2, 3, 4, 5]
. 这将产生
[1, 2, 3, 4, 5]
。
Alternatively you could merge both streams: 或者,您可以合并两个流:
Flux<Integer> mergeObjectWithStream = Flux.merge(existingStream, Flux.just(5));
That will produce a similar stream, however the 5
element could appear anywhere in the resulting flux. 这将产生类似的流,但是
5
元素可能会出现在结果磁通量的任何位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.