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

org.reactfx.AccumulateBetweenStream Maven / Gradle / Ivy

There is a newer version: 1.11
Show newest version
package org.reactfx;

import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

class AccumulateBetweenStream extends EventStreamBase {
    private final EventStream source;
    private final EventStream ticks;
    private final Function initialTransformation;
    private final BiFunction accumulation;
    private final Function> deconstruction;

    private boolean hasValue = false;
    private A accum = null;

    public AccumulateBetweenStream(
            EventStream source,
            EventStream ticks,
            Function initialTransformation,
            BiFunction accumulation,
            Function> deconstruction) {
        this.source = source;
        this.ticks = ticks;
        this.initialTransformation = initialTransformation;
        this.accumulation = accumulation;
        this.deconstruction = deconstruction;
    }

    @Override
    protected Subscription observeInputs() {
        Subscription s1 = source.subscribe(this::handleEvent);
        Subscription s2 = ticks.subscribe(this::handleTick);
        return s1.and(s2).and(this::reset);
    }

    private void handleEvent(T event) {
        if(hasValue) {
            accum = accumulation.apply(accum, event);
        } else {
            accum = initialTransformation.apply(event);
            hasValue = true;
        }
    }

    private void handleTick(Object tick) {
        if(hasValue) {
            List toEmit = deconstruction.apply(accum);
            reset();
            for(T t: toEmit) {
                emit(t);
            }
        }
    }

    private void reset() {
        hasValue = false;
        accum = null;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy