Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDoFinally.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.concurrent.atomic.AtomicInteger;
17
18 import io.reactivex.rxjava3.core.*;
19 import io.reactivex.rxjava3.disposables.Disposable;
20 import io.reactivex.rxjava3.exceptions.Exceptions;
21 import io.reactivex.rxjava3.functions.Action;
22 import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
23 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
24
25 /**
26 * Execute an action after an onSuccess, onError or a dispose event.
27 * <p>History: 2.0.1 - experimental
28 * @param <T> the value type
29 * @since 2.1
30 */
31 public final class SingleDoFinally<T> extends Single<T> {
32
33 final SingleSource<T> source;
34
35 final Action onFinally;
36
37 public SingleDoFinally(SingleSource<T> source, Action onFinally) {
38 this.source = source;
39 this.onFinally = onFinally;
40 }
41
42 @Override
43 protected void subscribeActual(SingleObserver<? super T> observer) {
44 source.subscribe(new DoFinallyObserver<>(observer, onFinally));
45 }
46
47 static final class DoFinallyObserver<T> extends AtomicInteger implements SingleObserver<T>, Disposable {
48
49 private static final long serialVersionUID = 4109457741734051389L;
50
51 final SingleObserver<? super T> downstream;
52
53 final Action onFinally;
54
55 Disposable upstream;
56
57 DoFinallyObserver(SingleObserver<? super T> actual, Action onFinally) {
58 this.downstream = actual;
59 this.onFinally = onFinally;
60 }
61
62 @Override
63 public void onSubscribe(Disposable d) {
64 if (DisposableHelper.validate(this.upstream, d)) {
65 this.upstream = d;
66
67 downstream.onSubscribe(this);
68 }
69 }
70
71 @Override
72 public void onSuccess(T t) {
73 downstream.onSuccess(t);
74 runFinally();
75 }
76
77 @Override
78 public void onError(Throwable t) {
79 downstream.onError(t);
80 runFinally();
81 }
82
83 @Override
84 public void dispose() {
85 upstream.dispose();
86 runFinally();
87 }
88
89 @Override
90 public boolean isDisposed() {
91 return upstream.isDisposed();
92 }
93
94 void runFinally() {
95 if (compareAndSet(0, 1)) {
96 try {
97 onFinally.run();
98 } catch (Throwable ex) {
99 Exceptions.throwIfFatal(ex);
100 RxJavaPlugins.onError(ex);
101 }
102 }
103 }
104 }
105 }