RxJava delay for each item of list emitted

后端 未结 15 1758
感情败类
感情败类 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:55

    I think it's exactly what you need. Take look:

    long startTime = System.currentTimeMillis();
    Observable.intervalRange(1, 5, 0, 50, TimeUnit.MILLISECONDS)
                    .timestamp(TimeUnit.MILLISECONDS)
                    .subscribe(emitTime -> {
                        System.out.println(emitTime.time() - startTime);
                    });
    
    0 讨论(0)
  • 2020-11-29 00:55

    you should be able to achieve this by using Timer operator. I tried with delay but couldn't achieve the desired output. Note nested operations done in flatmap operator.

        Observable.range(1,5)
                .flatMap(x -> Observable.timer(50 * x, TimeUnit.MILLISECONDS)
                            .map(y -> x))
                // attach timestamp
                .timestamp()
                .subscribe(timedIntegers ->
                        Log.i(TAG, "Timed String: "
                                + timedIntegers.value()
                                + " "
                                + timedIntegers.time()));
    
    0 讨论(0)
  • 2020-11-29 01:01

    The simplest way to do this seems to be just using concatMap and wrapping each item in a delayed Obserable.

    long startTime = System.currentTimeMillis();
    Observable.range(1, 5)
            .concatMap(i-> Observable.just(i).delay(50, TimeUnit.MILLISECONDS))
            .doOnNext(i-> System.out.println(
                    "Item: " + i + ", Time: " + (System.currentTimeMillis() - startTime) +"ms"))
            .toCompletable().await();
    

    Prints:

    Item: 1, Time: 51ms
    Item: 2, Time: 101ms
    Item: 3, Time: 151ms
    Item: 4, Time: 202ms
    Item: 5, Time: 252ms
    
    0 讨论(0)
提交回复
热议问题