Java reactor: how to generate flux from stdin?
•
Java
I want to read user generated messages from stdin asynchronously
Flux.from(stdinPublisher()) .subscribe(msg -> System.out.println("Received: " + msg));
So how do you implement such stdin publishers here?
Solution
be prone to. Sorry to disturb:)
import java.util.Scanner; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; @Component @Slf4j public class StdinProducerExample implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { Flux .create(sink -> { Scanner scanner = new Scanner(system.in); while (scanner.hasNext()) { sink.next(scanner.nextLine()); } }) .subscribeOn(Schedulers.newSingle("stdin publisher")) .subscribe(m -> log.info("User message: {}",m)); log.info("Started listening stdin"); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码