Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSingleMaybe.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.DisposableHelper;
19 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
20
21 public final class ObservableSingleMaybe<T> extends Maybe<T> {
22
23 final ObservableSource<T> source;
24
25 public ObservableSingleMaybe(ObservableSource<T> source) {
26 this.source = source;
27 }
28
29 @Override
30 public void subscribeActual(MaybeObserver<? super T> t) {
31 source.subscribe(new SingleElementObserver<>(t));
32 }
33
34 static final class SingleElementObserver<T> implements Observer<T>, Disposable {
35 final MaybeObserver<? super T> downstream;
36
37 Disposable upstream;
38
39 T value;
40
41 boolean done;
42
43 SingleElementObserver(MaybeObserver<? super T> downstream) {
44 this.downstream = downstream;
45 }
46
47 @Override
48 public void onSubscribe(Disposable d) {
49 if (DisposableHelper.validate(this.upstream, d)) {
50 this.upstream = d;
51 downstream.onSubscribe(this);
52 }
53 }
54
55 @Override
56 public void dispose() {
57 upstream.dispose();
58 }
59
60 @Override
61 public boolean isDisposed() {
62 return upstream.isDisposed();
63 }
64
65 @Override
66 public void onNext(T t) {
67 if (done) {
68 return;
69 }
70 if (value != null) {
71 done = true;
72 upstream.dispose();
73 downstream.onError(new IllegalArgumentException("Sequence contains more than one element!"));
74 return;
75 }
76 value = t;
77 }
78
79 @Override
80 public void onError(Throwable t) {
81 if (done) {
82 RxJavaPlugins.onError(t);
83 return;
84 }
85 done = true;
86 downstream.onError(t);
87 }
88
89 @Override
90 public void onComplete() {
91 if (done) {
92 return;
93 }
94 done = true;
95 T v = value;
96 value = null;
97 if (v == null) {
98 downstream.onComplete();
99 } else {
100 downstream.onSuccess(v);
101 }
102 }
103 }
104 }