Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleFromPublisher.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.single;
15
16 import java.util.NoSuchElementException;
17
18 import org.reactivestreams.*;
19
20 import io.reactivex.rxjava3.core.*;
21 import io.reactivex.rxjava3.disposables.Disposable;
22 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
23 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
24
25 public final class SingleFromPublisher<T> extends Single<T> {
26
27 final Publisher<? extends T> publisher;
28
29 public SingleFromPublisher(Publisher<? extends T> publisher) {
30 this.publisher = publisher;
31 }
32
33 @Override
34 protected void subscribeActual(final SingleObserver<? super T> observer) {
35 publisher.subscribe(new ToSingleObserver<T>(observer));
36 }
37
38 static final class ToSingleObserver<T> implements FlowableSubscriber<T>, Disposable {
39 final SingleObserver<? super T> downstream;
40
41 Subscription upstream;
42
43 T value;
44
45 boolean done;
46
47 volatile boolean disposed;
48
49 ToSingleObserver(SingleObserver<? super T> downstream) {
50 this.downstream = downstream;
51 }
52
53 @Override
54 public void onSubscribe(Subscription s) {
55 if (SubscriptionHelper.validate(this.upstream, s)) {
56 this.upstream = s;
57
58 downstream.onSubscribe(this);
59
60 s.request(Long.MAX_VALUE);
61 }
62 }
63
64 @Override
65 public void onNext(T t) {
66 if (done) {
67 return;
68 }
69 if (value != null) {
70 upstream.cancel();
71 done = true;
72 this.value = null;
73 downstream.onError(new IndexOutOfBoundsException("Too many elements in the Publisher"));
74 } else {
75 value = t;
76 }
77 }
78
79 @Override
80 public void onError(Throwable t) {
81 if (done) {
82 RxJavaPlugins.onError(t);
83 return;
84 }
85 done = true;
86 this.value = null;
87 downstream.onError(t);
88 }
89
90 @Override
91 public void onComplete() {
92 if (done) {
93 return;
94 }
95 done = true;
96 T v = this.value;
97 this.value = null;
98 if (v == null) {
99 downstream.onError(new NoSuchElementException("The source Publisher is empty"));
100 } else {
101 downstream.onSuccess(v);
102 }
103 }
104
105 @Override
106 public boolean isDisposed() {
107 return disposed;
108 }
109
110 @Override
111 public void dispose() {
112 disposed = true;
113 upstream.cancel();
114 }
115 }
116 }