All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jetlinks.rule.engine.defaults.CompositeEventBus Maven / Gradle / Ivy

There is a newer version: 1.2.2
Show newest version
package org.jetlinks.rule.engine.defaults;

import org.jetlinks.rule.engine.api.*;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class CompositeEventBus implements EventBus {

    private final List subBus = new CopyOnWriteArrayList<>();

    private final List pubBus = new CopyOnWriteArrayList<>();

    public CompositeEventBus addForSubscribe(EventBus... bus) {
        subBus.addAll(Arrays.asList(bus));
        return this;
    }

    public CompositeEventBus addForPublish(EventBus... bus) {
        pubBus.addAll(Arrays.asList(bus));
        return this;
    }

    @Override
    public  Flux subscribe(String topic, Decoder type) {
        return Flux.fromIterable(subBus)
                .map(eventBus -> eventBus.subscribe(topic, type))
                .as(Flux::merge);
    }

    @Override
    public  Mono publish(String topic, Encoder encoder, Publisher eventStream) {
        Flux source = Flux.from(eventStream).cache();

        return Flux.fromIterable(pubBus)
                .map(eventBus -> eventBus.publish(topic, encoder, source))
                .as(Flux::merge)
                .reduce(Math::addExact)
                .defaultIfEmpty(0);
    }

    @Override
    public Flux subscribe(String topic) {
        return Flux.fromIterable(subBus)
                .map(eventBus -> eventBus.subscribe(topic))
                .as(Flux::merge);
    }

    @Override
    public  Mono publish(String topic, Publisher event) {
        Flux source = Flux.from(event).cache();

        return Flux.fromIterable(pubBus)
                .map(eventBus -> eventBus.publish(topic, source))
                .as(Flux::merge)
                .reduce(Math::addExact)
                .defaultIfEmpty(0);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy