Debian Codegraph @

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