|
| 1 | +/* |
| 2 | + * Copyright (c) 2016-present, RxJava Contributors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in |
| 5 | + * compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License is |
| 10 | + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See |
| 11 | + * the License for the specific language governing permissions and limitations under the License. |
| 12 | + */ |
| 13 | + |
| 14 | +package io.reactivex.rxjava4.internal.operators.streamable; |
| 15 | + |
| 16 | +import java.util.concurrent.CompletionStage; |
| 17 | + |
| 18 | +import io.reactivex.rxjava4.annotations.NonNull; |
| 19 | +import io.reactivex.rxjava4.core.*; |
| 20 | +import io.reactivex.rxjava4.disposables.*; |
| 21 | +import io.reactivex.rxjava4.internal.fuseable.HasUpstreamStreamableSource; |
| 22 | + |
| 23 | +public record StreamableTake<T>(Streamable<T> source, long count) |
| 24 | +implements Streamable<T>, HasUpstreamStreamableSource<T> { |
| 25 | + |
| 26 | + @Override |
| 27 | + public @NonNull Streamer<@NonNull T> stream(@NonNull StreamerCancellation cancellation) { |
| 28 | + var dsc = cancellation.derive(); |
| 29 | + return new TakeStreamer<>(source.stream(dsc), count, dsc); |
| 30 | + } |
| 31 | + |
| 32 | + static final class TakeStreamer<T> implements Streamer<T> { |
| 33 | + final Streamer<T> upstream; |
| 34 | + |
| 35 | + final Disposable upstreamDisposable; |
| 36 | + |
| 37 | + long remaining; |
| 38 | + |
| 39 | + TakeStreamer(Streamer<T> upstream, long count, Disposable upstreamDisposable) { |
| 40 | + this.upstream = upstream; |
| 41 | + this.upstreamDisposable = upstreamDisposable; |
| 42 | + this.remaining = count; |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public @NonNull CompletionStage<Boolean> next() { |
| 47 | + if (remaining-- <= 0L) { |
| 48 | + upstreamDisposable.dispose(); |
| 49 | + return NEXT_FALSE; |
| 50 | + } |
| 51 | + return upstream.next(); |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public @NonNull T current() { |
| 56 | + return upstream.current(); |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public @NonNull CompletionStage<Void> finish() { |
| 61 | + return upstream.finish(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments