发射每个对象之间有延迟的对象数组

时间:2016-05-13 19:02:28

标签: java rx-java

我有一个对象数组,我想发射每个对象,然后延迟5秒。最后,只有在发出所有物体后才完成。

这是我的代码,但并不是那么做,

public class SequentialLoopWithDelayTest {

    @Test
    public void test() {
        System.out.println("Start: " + DateTime.now().toString());
        rx.Observable.from(new String[] {"Test_1", "Test_2", "Test_3"}) 
        .flatMap(str -> {
            return printObservable(str)
            .delay(5, TimeUnit.SECONDS);
        })
            .subscribe(results -> { 
                System.out.println("End: " + DateTime.now().toString());
        });

    }

    private static rx.Observable<String> printObservable(String str) {
        System.out.println(DateTime.now().toString() + ", " + str);
        return rx.Observable.just(str);
    }
}

我该如何解决这个问题?

注意:我不能使用任何阻止!

谢谢: - )

2 个答案:

答案 0 :(得分:1)

使用区间

创建可观察的Zip
List<String> testList = Arrays.asList(new String[] {"Test_1", "Test_2", "Test_3"});
Observable<String> test = Observable.from(testList).zipWith(Observable.interval(0,5000,TimeUnit.MILLISECONDS), (a,b) -> a);
test.subscribe(value -> System.out.println(value + " Emitted at : " + DateTime.now().toString()), error->{},()-> System.out.print("Completed"));

完整代码

import rx.Observable;
import rx.Subscriber;
import java.util.concurrent.TimeUnit;
import java.util.Arrays;
import java.util.List;
import org.joda.time.DateTime;

class TimerTest {
    public static void main(String[] args) {
        List<String> testList = Arrays.asList(new String[] {"Test_1", "Test_2", "Test_3"});
        Observable<String> test = Observable.from(testList).zipWith(Observable.interval(0,5000,TimeUnit.MILLISECONDS), (a,b) -> a);
        test.subscribe(value -> System.out.println(value + " Emitted at : " + DateTime.now().toString()), error->{},()-> System.out.print("Completed"));

        try {
            // Sleep so the program doesn't exit immediately
            Thread.sleep(50000);
        }
        catch (Exception e) {

        }
    }
}

延迟完成

Observable<String> test2 = test.concatWith(Observable.<String>empty().delay(2000,TimeUnit.MILLISECONDS))

答案 1 :(得分:0)

作为对最后一个答案的评论(没有足够的代表评论),而不是使用Thread.sleep,你可以添加'toBlocking'调用:

test.toBlocking().subscribe(...