RxJava delay for each item of list emitted

后端 未结 15 1822
感情败类
感情败类 2020-11-29 00:14

I\'m struggling to implement something I assumed would be fairly simple in Rx.

I have a list of items, and I want to have each item emitted with a delay.

It

15条回答
  •  悲&欢浪女
    2020-11-29 00:45

    You can add a delay between emitted items by using flatMap, maxConcurrent and delay()

    Here is an example - emit 0..4 with delay

    @Test
    fun testEmitWithDelays() {
        val DELAY = 500L
        val COUNT = 5
    
        val latch = CountDownLatch(1)
        val startMoment = System.currentTimeMillis()
        var endMoment : Long = 0
    
        Observable
            .range(0, COUNT)
            .flatMap( { Observable.just(it).delay(DELAY, TimeUnit.MILLISECONDS) }, 1) // maxConcurrent = 1
            .subscribe(
                    { println("... value: $it, ${System.currentTimeMillis() - startMoment}") },
                    {},
                    {
                        endMoment = System.currentTimeMillis()
                        latch.countDown()
                    })
    
        latch.await()
    
        assertTrue { endMoment - startMoment >= DELAY * COUNT }
    }
    
    ... value: 0, 540
    ... value: 1, 1042
    ... value: 2, 1544
    ... value: 3, 2045
    ... value: 4, 2547
    

提交回复
热议问题