Debian Codegraph @

src/main/java/io/reactivex/rxjava3/observers/DisposableCompletableObserver.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.observers;
15
16 import java.util.concurrent.atomic.AtomicReference;
17
18 import io.reactivex.rxjava3.annotations.NonNull;
19 import io.reactivex.rxjava3.core.CompletableObserver;
20 import io.reactivex.rxjava3.disposables.Disposable;
21 import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
22 import io.reactivex.rxjava3.internal.util.EndConsumerHelper;
23
24 /**
25 * An abstract {@link CompletableObserver} that allows asynchronous cancellation by implementing Disposable.
26 *
27 * <p>All pre-implemented final methods are thread-safe.
28 *
29 * <p>Like all other consumers, {@code DisposableCompletableObserver} can be subscribed only once.
30 * Any subsequent attempt to subscribe it to a new source will yield an
31 * {@link IllegalStateException} with message {@code "It is not allowed to subscribe with a(n) <class name> multiple times."}.
32 *
33 * <p>Implementation of {@link #onStart()}, {@link #onError(Throwable)} and
34 * {@link #onComplete()} are not allowed to throw any unchecked exceptions.
35 *
36 * <p>Example<pre><code>
37 * Disposable d =
38 * Completable.complete().delay(1, TimeUnit.SECONDS)
39 * .subscribeWith(new DisposableMaybeObserver&lt;Integer&gt;() {
40 * &#64;Override public void onStart() {
41 * System.out.println("Start!");
42 * }
43 * &#64;Override public void onError(Throwable t) {
44 * t.printStackTrace();
45 * }
46 * &#64;Override public void onComplete() {
47 * System.out.println("Done!");
48 * }
49 * });
50 * // ...
51 * d.dispose();
52 * </code></pre>
53 */
54 public abstract class DisposableCompletableObserver implements CompletableObserver, Disposable {
55
56 final AtomicReference<Disposable> upstream = new AtomicReference<>();
57
58 @Override
59 public final void onSubscribe(@NonNull Disposable d) {
60 if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) {
61 onStart();
62 }
63 }
64
65 /**
66 * Called once the single upstream {@link Disposable} is set via {@link #onSubscribe(Disposable)}.
67 */
68 protected void onStart() {
69 }
70
71 @Override
72 public final boolean isDisposed() {
73 return upstream.get() == DisposableHelper.DISPOSED;
74 }
75
76 @Override
77 public final void dispose() {
78 DisposableHelper.dispose(upstream);
79 }
80 }