在 RxJava

时间:2021-01-10 12:23:53

标签: java rx-java

使用RxJava,是否可以创建一个观察者以n秒的间隔做一些动作?

我想从控制台输入流创建一个 observable,在观察者中,我想以 n 秒的间隔对该值执行一些操作。类似的东西:

StringObservable.from(System.in)
            .subscribe(input -> {
                // 1. read the input value and store it once the value is 
                // received
                //
                // 2. for every n seconds, do some action  
            }); 

我曾尝试使用 while true 循环,但这会永远阻塞程序的其余部分。

StringObservable.from(System.in)
                .subscribe(input -> {
                    // 1. read the input value and store it once the 
                    //value is received
                    //
                    while (true) {
                      try {
                        Thread.sleep(5000);
                      } catch (InterruptedException e) {
                        e.printStackTrace();
                      }
                    
                      // do some action
                    } 
                }); 

1 个答案:

答案 0 :(得分:0)

combineLatest试试interval

Observable.combineLatest(
    StringObservable.from(System.in),
    Observable.interval(1, TimeUnit.SECONDS),
    (input, time) -> String.format("%d - %s%n", time, input)
)
.subscribe(System.out::println);
相关问题