Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableTake.java

raw
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.rxjava3.internal.operators.observable;
15
16 import io.reactivex.rxjava3.core.*;
17 import io.reactivex.rxjava3.disposables.Disposable;
18 import io.reactivex.rxjava3.internal.disposables.*;
19 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
20
21 public final class ObservableTake<T> extends AbstractObservableWithUpstream<T, T> {
22 final long limit;
23 public ObservableTake(ObservableSource<T> source, long limit) {
24 super(source);
25 this.limit = limit;
26 }
27
28 @Override
29 protected void subscribeActual(Observer<? super T> observer) {
30 source.subscribe(new TakeObserver<>(observer, limit));
31 }
32
33 static final class TakeObserver<T> implements Observer<T>, Disposable {
34 final Observer<? super T> downstream;
35
36 boolean done;
37
38 Disposable upstream;
39
40 long remaining;
41 TakeObserver(Observer<? super T> actual, long limit) {
42 this.downstream = actual;
43 this.remaining = limit;
44 }
45
46 @Override
47 public void onSubscribe(Disposable d) {
48 if (DisposableHelper.validate(this.upstream, d)) {
49 upstream = d;
50 if (remaining == 0) {
51 done = true;
52 d.dispose();
53 EmptyDisposable.complete(downstream);
54 } else {
55 downstream.onSubscribe(this);
56 }
57 }
58 }
59
60 @Override
61 public void onNext(T t) {
62 if (!done && remaining-- > 0) {
63 boolean stop = remaining == 0;
64 downstream.onNext(t);
65 if (stop) {
66 onComplete();
67 }
68 }
69 }
70
71 @Override
72 public void onError(Throwable t) {
73 if (done) {
74 RxJavaPlugins.onError(t);
75 return;
76 }
77
78 done = true;
79 upstream.dispose();
80 downstream.onError(t);
81 }
82
83 @Override
84 public void onComplete() {
85 if (!done) {
86 done = true;
87 upstream.dispose();
88 downstream.onComplete();
89 }
90 }
91
92 @Override
93 public void dispose() {
94 upstream.dispose();
95 }
96
97 @Override
98 public boolean isDisposed() {
99 return upstream.isDisposed();
100 }
101 }
102 }