|
16 | 16 | import java.util.NoSuchElementException; |
17 | 17 | import java.util.concurrent.CompletionStage; |
18 | 18 |
|
19 | | -import io.reactivex.rxjava4.annotations.NonNull; |
| 19 | +import io.reactivex.rxjava4.annotations.*; |
20 | 20 | import io.reactivex.rxjava4.disposables.*; |
21 | 21 |
|
22 | 22 | /** |
@@ -69,4 +69,34 @@ default CompletionStage<Boolean> next() { |
69 | 69 | default void close() { |
70 | 70 | cancel().toCompletableFuture().join(); |
71 | 71 | } |
| 72 | + |
| 73 | + /** |
| 74 | + * The {@code await} keyword for async/await. |
| 75 | + * @param <T> the type of the returned value if any. |
| 76 | + * @param stage the stage to await virtual-blockingly |
| 77 | + * @return the awaited value |
| 78 | + */ |
| 79 | + @Nullable |
| 80 | + static <T> T await(@NonNull CompletionStage<T> stage) { |
| 81 | + return await(stage, null); |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * The cancellable {@code await} keyword for async/await. |
| 86 | + * @param <T> the type of the returned value if any. |
| 87 | + * @param stage the stage to await virtual-blockingly |
| 88 | + * @param cancellation the container that can trigger a cancellation on demand |
| 89 | + * @return the awaited value |
| 90 | + */ |
| 91 | + @Nullable |
| 92 | + static <T> T await(@NonNull CompletionStage<T> stage, @Nullable DisposableContainer cancellation) { |
| 93 | + var f = stage.toCompletableFuture(); |
| 94 | + if (cancellation == null) { |
| 95 | + return f.join(); |
| 96 | + } |
| 97 | + var d = Disposable.fromFuture(f, true); |
| 98 | + try (var _ = cancellation.subscribe(d)) { |
| 99 | + return f.join(); |
| 100 | + } |
| 101 | + } |
72 | 102 | } |
0 commit comments