Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reactor: How to produce Flux from stdin?

I would like to asynchronously read messages produced by user from stdin. Something like:

Flux.from(stdinPublisher()) 
    .subscribe(msg -> System.out.println("Received: " + msg));

So how to implement such stdin publisher here?

like image 757
Bullet-tooth Avatar asked Jan 03 '23 17:01

Bullet-tooth


1 Answers

It was easy. Sorry for 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");
  }

}
like image 169
Bullet-tooth Avatar answered Jan 05 '23 16:01

Bullet-tooth