-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
580327a
commit b1357eb
Showing
3 changed files
with
101 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package org.davidmoten.kool; | ||
|
||
import java.util.ArrayDeque; | ||
import java.util.NoSuchElementException; | ||
import java.util.Queue; | ||
|
||
public final class Publisher<T> implements Stream<T> { | ||
|
||
private final StreamIterable<T> stream; | ||
private final Queue<T> queue; | ||
|
||
public Publisher(StreamIterable<T> stream) { | ||
this.stream = stream; | ||
this.queue = new ArrayDeque<>(); | ||
} | ||
|
||
@Override | ||
public StreamIterator<T> iterator() { | ||
return new StreamIterator<T>() { | ||
|
||
StreamIterator<T> it = stream.iteratorNullChecked(); | ||
boolean itHasNext = true; | ||
boolean disposed = false; | ||
|
||
@Override | ||
public boolean hasNext() { | ||
load(); | ||
if (itHasNext) { | ||
return true; | ||
} else { | ||
return !queue.isEmpty(); | ||
} | ||
} | ||
|
||
@Override | ||
public T next() { | ||
load(); | ||
if (itHasNext) { | ||
return it.next(); | ||
} else if (queue.isEmpty()) { | ||
throw new NoSuchElementException(); | ||
} else { | ||
return queue.poll(); | ||
} | ||
} | ||
|
||
@Override | ||
public void dispose() { | ||
if (!disposed) { | ||
it.dispose(); | ||
} | ||
disposed = true; | ||
} | ||
|
||
private void load() { | ||
if (itHasNext) { | ||
itHasNext = it.hasNext(); | ||
if (!itHasNext) { | ||
it.dispose(); | ||
} | ||
} | ||
} | ||
}; | ||
} | ||
|
||
public void onNext(T value) { | ||
queue.add(value); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters