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

org.davidmoten.kool.internal.operators.stream.DoOnEmpty Maven / Gradle / Ivy

There is a newer version: 0.1.35
Show newest version
package org.davidmoten.kool.internal.operators.stream;

import java.util.NoSuchElementException;

import org.davidmoten.kool.Stream;
import org.davidmoten.kool.StreamIterator;
import org.davidmoten.kool.function.Action;

public final class DoOnEmpty implements Stream {

    private final Stream stream;
    private final Action action;

    public DoOnEmpty(Stream stream, Action action) {
        this.stream = stream;
        this.action = action;
    }

    @Override
    public StreamIterator iterator() {
        return new StreamIterator() {

            StreamIterator it = stream.iteratorNullChecked();
            boolean checkedForEmpty;

            @Override
            public boolean hasNext() {
                check();
                return it.hasNext();
            }

            @Override
            public T next() {
                check();
                if (it == null) {
                    throw new NoSuchElementException();
                } else {
                    return it.nextNullChecked();
                }
            }

            @Override
            public void dispose() {
                if (it != null) {
                    it.dispose();
                    // release for gc
                    it = null;
                }
            }

            private void check() {
                if (!checkedForEmpty) {
                    if (!it.hasNext()) {
                        action.callUnchecked();
                    }
                    checkedForEmpty = true;
                }
            }

        };
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy