简体   繁体   English

等到上一个事件完成 Rx

[英]Wait until previous event finish Rx

In my code, I have events that need to be processed sequentially and others in parallel.在我的代码中,我有一些事件需要按顺序处理,而其他事件需要并行处理。

I managed to do the parallel part but I can't do the sequential version.我设法做了并行部分,但我不能做顺序版本。

event.ofType(Message.class)
    .groupBy(Message::getGroup)
    .flatMap(g -> {
        if (g.getKey() == Message.GROUP_PARALLEL)
            return g.flatMap(m -> Observable.just(m)
                        .observeOn(Schedulers.computation())
                        .doOnNext(this::send)
                        .delay(m.getRetryInterval(), TimeUnit.SECONDS)
                        .repeat(m.getRetryCount())
                        .takeUntil(event.ofType(Sent.class)
                            .filter(a -> a.getId() == m.getId())
                        )
                        .map(s -> m)
                    );
        else if (g.getKey() == Message.GROUP_SEQUENTIAL) {
            // ?
        }
    })

I would like to implement it like this:我想这样实现它:

When an event is received
    If the previous event is still being processed, wait before emission
    Process the event (blocking)

So:所以:

    event.subscribeOn(Schedulers.computation())
        .waitUntilPreviousComplete()
        .flatMap(this::processEvent) // we assume it take 1 seconds to complete
        .susbcribe(this::processed, this::onError);

    event.onNext(Event.A)
    event.onNext(Event.B)
    event.onNext(Event.C)

Should result:应该结果:

    12h00:00 processed call with event A
    12h00:01 processed call with event B
    12h00:02 processed call with event C

So i want something looking like a Queue.所以我想要一些看起来像队列的东西。 I tried weird things with HashMap and Subjects but Im sure there is a clean way to do it.我用 HashMap 和 Subjects 尝试了奇怪的事情,但我确信有一种干净的方法可以做到这一点。 How can I implement that?我该如何实施?

It sounds like you're looking for concatMap .听起来您正在寻找concatMap That operator will subscribe to items emitted by upstream sequentially, and won't move on to the next item until the previous on completes.该操作员将按顺序订阅上游发出的项目,并且在前一个 on 完成之前不会移动到下一个项目。 So your example code would look like this:所以你的示例代码看起来像这样:

event.subscribeOn(Schedulers.computation())
    .concatMap(this::processEvent)
    .subscribe(this::processed, this::onError);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM