在可观察项RxJava之间添加延迟 [英] Adding delay between Observable Items RxJava

查看:367
本文介绍了在可观察项RxJava之间添加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从对象列表中创建了一个可观察的对象.对于列表中的每个对象,我都会发出网络请求,但我想在列表中的每个项目之间放置一个延迟,以使请求间隔一些.这是我的代码段.

I have an observable I've created from a list of objects. For each object in the list I make a network request but I'd like to put a delay between each item in the list as to space out the requests a bit. Here's a snippet of my code.

return Observable.from(documentGroupModels).flatMap(new Func1<DocumentGroupModel, Observable<Boolean>>() {
        @Override
        public Observable<Boolean> call(DocumentGroupModel documentGroupModel) {
            return refreshDocumentWithUri(documentGroupModel.getUri(), documentGroupModel.sectionGroupId,
                                          includeExceptions, false);
        }
    });

就我所知,在这种情况下,使用延迟或缓冲不太有效.

Using delay or buffer doesn't quite work for this scenario as far as I can tell.

推荐答案

如果延迟是静态的,则可以结合使用 Zip interval 运算符,因此您可以每次在间隔上进行配置时,都会发出一个zip项目.

You can use a combination of Zip and interval operator if your delay is static, so you can emit an item of your zip every time configure on your interval.

检查示例

       @Test
public void delaySteps() {
    long start = System.currentTimeMillis();
    Subscription subscription =
            Observable.zip(Observable.from(Arrays.asList(1, 2, 3)), Observable.interval(200, TimeUnit.MILLISECONDS),
                           (i, t) -> i)
                    .subscribe(n -> System.out.println("time:" + (System.currentTimeMillis() - start)));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(3000, TimeUnit.MILLISECONDS);
}

您还可以使用列表创建一个Observable并使用 concatMap ,然后可以对发射的每个项目使用 delay .也许此解决方案更优雅,而且没有Hacky

Also you can create an Observable with your list and use concatMap, then you can use delay for every item emitted. Maybe this solution is more elegant and no so Hacky

      @Test
public void delayObservableList() {
    Observable.from(Arrays.asList(1, 2, 3, 4, 5))
            .concatMap(s -> Observable.just(s).delay(100, TimeUnit.MILLISECONDS))
            .subscribe(n -> System.out.println(n + " emitted"),
                       e -> {
                       },
                       () -> System.out.println("All emitted"));
    new TestSubscriber().awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);

}

您可以在此处看到另一个延迟示例 https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableDelay.java

You can see another examples of delay here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableDelay.java

这篇关于在可观察项RxJava之间添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆