我已经编写了一个示例,使用延迟来等待另一个可观察对象,然后再发出您的数据。
class SimpleTest {
val testScheduler = TestScheduler()
@Test
fun test() {
fooObservable()
.doOnNext { logger("Next", it.toString()) }
.delay { Observable.timer(5, TimeUnit.SECONDS, testScheduler) }
.subscribe { logger("Delayed", it.toString()) }
testScheduler.advanceTimeBy(10, TimeUnit.SECONDS)
}
fun fooObservable(): Observable<Int> {
return Observable.just(1, 2, 3, 4)
}
fun logger(tag: String, message: String): Unit {
val formattedDate = Date(testScheduler.now()).format()
System.out.println("$tag @ $formattedDate: $message")
}
fun Date.format(): String {
return SimpleDateFormat("HH:mm:ss.SSS", Locale.US).format(this)
}
}
我使用了一个 5 秒的计时器来模拟您的次要观测值。
此代码打印该输出:
Next @ 21:00:00.000: 1
Next @ 21:00:00.000: 2
Next @ 21:00:00.000: 3
Next @ 21:00:00.000: 4
Delayed @ 21:00:05.000: 1
Delayed @ 21:00:05.000: 2
Delayed @ 21:00:05.000: 3
Delayed @ 21:00:05.000: 4