[英]How can I add in reactive Java a new Object to an existing stream?
假設我已經有一個響應流,現在我想向此現有流添加一個對象。 我怎樣才能做到這一點?
這是我發現的方法 ,這是走的路嗎?
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");
}
}
假設這是您現有的流:
Flux<Integer> existingStream = Flux.just(1, 2, 3, 4);
您可以連接兩個流:
Flux<Integer> appendObjectToStream = Flux.concat(existingStream, Flux.just(5));
這將產生[1, 2, 3, 4, 5]
。
或者,您可以合並兩個流:
Flux<Integer> mergeObjectWithStream = Flux.merge(existingStream, Flux.just(5));
這將產生類似的流,但是5
元素可能會出現在結果磁通量的任何位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.