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

org.reactfx.AccumulateUntilLaterStream Maven / Gradle / Ivy

There is a newer version: 2.0-M5
Show newest version
package org.reactfx;

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

class AccumulateUntilLaterStream extends EventStreamBase {
    private final EventStream source;
    private final Function initialTransformation;
    private final BiFunction accumulation;
    private final Function> deconstruction;
    private final Executor eventThreadExecutor;

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

    public AccumulateUntilLaterStream(
            EventStream source,
            Function initialTransformation,
            BiFunction accumulation,
            Function> deconstruction,
            Executor eventThreadExecutor) {
        this.source = source;
        this.initialTransformation = initialTransformation;
        this.accumulation = accumulation;
        this.deconstruction = deconstruction;
        this.eventThreadExecutor = eventThreadExecutor;
    }

    @Override
    protected Subscription observeInputs() {
        return source.subscribe(this::handleEvent);
    }

    private void handleEvent(T event) {
        if(hasValue) {
            accum = accumulation.apply(accum, event);
            // emission already scheduled
        } else {
            accum = initialTransformation.apply(event);
            hasValue = true;
            eventThreadExecutor.execute(this::emitAccum);
        }
    }

    private void emitAccum() {
        assert hasValue;
        hasValue = false;
        List toEmit = deconstruction.apply(accum);
        accum = null;
        for(T t: toEmit) {
            emit(t);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy