Created
June 6, 2017 12:11
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
import java.util.Arrays; | |
import java.util.Collection; | |
import java.util.Iterator; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.function.Supplier; | |
import java.util.stream.Stream; | |
import java.util.stream.StreamSupport; | |
/** | |
* @author Yahor Radtsevich | |
*/ | |
public class CompletableStream { | |
private static <T> Stream<T> toStream(CompletableFuture<Collection<T>> future) { | |
Iterator<T> asyncIterator = new AsyncIterator<>(future::join); | |
Iterable<T> iterable = () -> asyncIterator; | |
return StreamSupport.stream(iterable.spliterator(), false); | |
} | |
private static class AsyncIterator<T> implements Iterator<T> { | |
private final Supplier<Collection<T>> collectionSupplier; | |
Iterator<T> iterator; | |
AsyncIterator(Supplier<Collection<T>> collectionSupplier) { | |
this.collectionSupplier = collectionSupplier; | |
} | |
@Override | |
public boolean hasNext() { | |
return getIterator().hasNext(); | |
} | |
@Override | |
public T next() { | |
return getIterator().next(); | |
} | |
private Iterator<T> getIterator() { | |
if (iterator == null) { | |
iterator = collectionSupplier.get().iterator(); | |
} | |
return iterator; | |
} | |
} | |
public static void main(String[] args) { | |
CompletableFuture<Collection<String>> future = CompletableFuture.supplyAsync(() -> { | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("COMPLETING FEATURE"); | |
return Arrays.asList("a", "b", "c"); | |
}); | |
System.out.println("BEFORE"); | |
Stream<String> targetStream = toStream(future); | |
System.out.println("AFTER"); | |
targetStream.forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment