Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDoOnSubscribe.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 io.reactivex.rxjava3.core.*;
17 import io.reactivex.rxjava3.disposables.Disposable;
18 import io.reactivex.rxjava3.exceptions.Exceptions;
19 import io.reactivex.rxjava3.functions.Consumer;
20 import io.reactivex.rxjava3.internal.disposables.EmptyDisposable;
21 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
22
23 /**
24 * Calls a callback when the upstream calls onSubscribe with a disposable.
25 *
26 * @param <T> the value type
27 */
28 public final class SingleDoOnSubscribe<T> extends Single<T> {
29
30 final SingleSource<T> source;
31
32 final Consumer<? super Disposable> onSubscribe;
33
34 public SingleDoOnSubscribe(SingleSource<T> source, Consumer<? super Disposable> onSubscribe) {
35 this.source = source;
36 this.onSubscribe = onSubscribe;
37 }
38
39 @Override
40 protected void subscribeActual(final SingleObserver<? super T> observer) {
41 source.subscribe(new DoOnSubscribeSingleObserver<>(observer, onSubscribe));
42 }
43
44 static final class DoOnSubscribeSingleObserver<T> implements SingleObserver<T> {
45
46 final SingleObserver<? super T> downstream;
47
48 final Consumer<? super Disposable> onSubscribe;
49
50 boolean done;
51
52 DoOnSubscribeSingleObserver(SingleObserver<? super T> actual, Consumer<? super Disposable> onSubscribe) {
53 this.downstream = actual;
54 this.onSubscribe = onSubscribe;
55 }
56
57 @Override
58 public void onSubscribe(Disposable d) {
59 try {
60 onSubscribe.accept(d);
61 } catch (Throwable ex) {
62 Exceptions.throwIfFatal(ex);
63 done = true;
64 d.dispose();
65 EmptyDisposable.error(ex, downstream);
66 return;
67 }
68
69 downstream.onSubscribe(d);
70 }
71
72 @Override
73 public void onSuccess(T value) {
74 if (done) {
75 return;
76 }
77 downstream.onSuccess(value);
78 }
79
80 @Override
81 public void onError(Throwable e) {
82 if (done) {
83 RxJavaPlugins.onError(e);
84 return;
85 }
86 downstream.onError(e);
87 }
88 }
89
90 }