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

org.reactfx.FlatMapStream Maven / Gradle / Ivy

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

import java.util.Optional;
import java.util.function.Function;

/**
 * See {@link EventStream#flatMap(Function)}
 */
class FlatMapStream extends EventStreamBase {
    private final EventStream source;
    private final Function> mapper;

    private Subscription mappedSubscription = Subscription.EMPTY;

    public FlatMapStream(
            EventStream src,
            Function> f) {
        this.source = src;
        this.mapper = f;
    }

    @Override
    protected Subscription observeInputs() {
        Subscription s = source.subscribe(t -> {
            mappedSubscription.unsubscribe();
            mappedSubscription = mapper.apply(t).subscribe(this::emit);
        });
        return () -> {
            s.unsubscribe();
            mappedSubscription.unsubscribe();
            mappedSubscription = Subscription.EMPTY;
        };
    }
}

class FlatMapOptStream extends EventStreamBase {
    private final EventStream source;
    private final Function> mapper;

    public FlatMapOptStream(
            EventStream src,
            Function> f) {
        this.source = src;
        this.mapper = f;
    }

    @Override
    protected Subscription observeInputs() {
        return source.subscribe(t -> mapper.apply(t).ifPresent(this::emit));
    }
}