gpt4 book ai didi

java - 发射对象数组,每个对象之间有延迟

转载 作者:行者123 更新时间:2023-12-01 09:55:58 24 4
gpt4 key购买 nike

我有一个对象数组,我想发出每个对象,然后延迟 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);
}
}

我该如何解决这个问题?

注意:我无法使用任何阻止!

谢谢:-)

最佳答案

使用间隔创建的可观察值进行压缩

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))

关于java - 发射对象数组,每个对象之间有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com