|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package groovy.concurrent; |
| 20 | + |
| 21 | +/** |
| 22 | + * Asynchronous iteration abstraction, analogous to C#'s |
| 23 | + * {@code IAsyncEnumerable<T>} or JavaScript's async iterables. |
| 24 | + * <p> |
| 25 | + * Used with the {@code for await} syntax: |
| 26 | + * <pre> |
| 27 | + * for await (item in asyncStream) { |
| 28 | + * process(item) |
| 29 | + * } |
| 30 | + * </pre> |
| 31 | + * <p> |
| 32 | + * Third-party reactive types (Reactor {@code Flux}, RxJava {@code Observable}) |
| 33 | + * can be adapted to {@code AsyncStream} via {@link AwaitableAdapter}. |
| 34 | + * |
| 35 | + * @param <T> the element type |
| 36 | + * @see AwaitableAdapter |
| 37 | + * @since 6.0.0 |
| 38 | + */ |
| 39 | +public interface AsyncStream<T> { |
| 40 | + |
| 41 | + /** |
| 42 | + * Asynchronously advances to the next element. Returns an {@link Awaitable} |
| 43 | + * that completes with {@code true} if an element is available, or |
| 44 | + * {@code false} if the stream is exhausted. |
| 45 | + */ |
| 46 | + Awaitable<Boolean> moveNext(); |
| 47 | + |
| 48 | + /** |
| 49 | + * Returns the current element. Must only be called after {@link #moveNext()} |
| 50 | + * has completed with {@code true}. |
| 51 | + */ |
| 52 | + T getCurrent(); |
| 53 | + |
| 54 | + /** |
| 55 | + * Returns an empty {@code AsyncStream} that completes immediately. |
| 56 | + */ |
| 57 | + @SuppressWarnings("unchecked") |
| 58 | + static <T> AsyncStream<T> empty() { |
| 59 | + return (AsyncStream<T>) EMPTY; |
| 60 | + } |
| 61 | + |
| 62 | + /** Singleton empty stream instance. */ |
| 63 | + AsyncStream<Object> EMPTY = new AsyncStream<>() { |
| 64 | + @Override public Awaitable<Boolean> moveNext() { return Awaitable.of(false); } |
| 65 | + @Override public Object getCurrent() { return null; } |
| 66 | + }; |
| 67 | +} |
0 commit comments