Debian Codegraph @

src/main/java/io/reactivex/rxjava3/observers/ResourceObserver.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.Objects;
17 import java.util.concurrent.atomic.AtomicReference;
18
19 import io.reactivex.rxjava3.annotations.NonNull;
20 import io.reactivex.rxjava3.core.Observer;
21 import io.reactivex.rxjava3.disposables.Disposable;
22 import io.reactivex.rxjava3.internal.disposables.*;
23 import io.reactivex.rxjava3.internal.util.EndConsumerHelper;
24
25 /**
26 * An abstract {@link Observer} that allows asynchronous cancellation of its subscription and associated resources.
27 *
28 * <p>All pre-implemented final methods are thread-safe.
29 *
30 * <p>To release the associated resources, one has to call {@link #dispose()}
31 * in {@code onError()} and {@code onComplete()} explicitly.
32 *
33 * <p>Use {@link #add(Disposable)} to associate resources (as {@link io.reactivex.rxjava3.disposables.Disposable Disposable}s)
34 * with this {@code ResourceObserver} that will be cleaned up when {@link #dispose()} is called.
35 * Removing previously associated resources is not possible but one can create a
36 * {@link io.reactivex.rxjava3.disposables.CompositeDisposable CompositeDisposable}, associate it with this
37 * {@code ResourceObserver} and then add/remove resources to/from the {@code CompositeDisposable}
38 * freely.
39 *
40 * <p>Use the {@link #dispose()} to dispose the sequence from within an
41 * {@code onNext} implementation.
42 *
43 * <p>Like all other consumers, {@code ResourceObserver} can be subscribed only once.
44 * Any subsequent attempt to subscribe it to a new source will yield an
45 * {@link IllegalStateException} with message {@code "It is not allowed to subscribe with a(n) <class name> multiple times."}.
46 *
47 * <p>Implementation of {@link #onStart()}, {@link #onNext(Object)}, {@link #onError(Throwable)}
48 * and {@link #onComplete()} are not allowed to throw any unchecked exceptions.
49 * If for some reason this can't be avoided, use {@link io.reactivex.rxjava3.core.Observable#safeSubscribe(io.reactivex.rxjava3.core.Observer)}
50 * instead of the standard {@code subscribe()} method.
51 *
52 * <p>Example<pre><code>
53 * Disposable d =
54 * Observable.range(1, 5)
55 * .subscribeWith(new ResourceObserver&lt;Integer&gt;() {
56 * &#64;Override public void onStart() {
57 * add(Schedulers.single()
58 * .scheduleDirect(() -&gt; System.out.println("Time!"),
59 * 2, TimeUnit.SECONDS));
60 * request(1);
61 * }
62 * &#64;Override public void onNext(Integer t) {
63 * if (t == 3) {
64 * dispose();
65 * }
66 * System.out.println(t);
67 * }
68 * &#64;Override public void onError(Throwable t) {
69 * t.printStackTrace();
70 * dispose();
71 * }
72 * &#64;Override public void onComplete() {
73 * System.out.println("Done!");
74 * dispose();
75 * }
76 * });
77 * // ...
78 * d.dispose();
79 * </code></pre>
80 *
81 * @param <T> the value type
82 */
83 public abstract class ResourceObserver<T> implements Observer<T>, Disposable {
84 /** The active subscription. */
85 private final AtomicReference<Disposable> upstream = new AtomicReference<>();
86
87 /** The resource composite, can never be null. */
88 private final ListCompositeDisposable resources = new ListCompositeDisposable();
89
90 /**
91 * Adds a resource to this {@code ResourceObserver}.
92 *
93 * @param resource the resource to add
94 *
95 * @throws NullPointerException if resource is {@code null}
96 */
97 public final void add(@NonNull Disposable resource) {
98 Objects.requireNonNull(resource, "resource is null");
99 resources.add(resource);
100 }
101
102 @Override
103 public final void onSubscribe(Disposable d) {
104 if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) {
105 onStart();
106 }
107 }
108
109 /**
110 * Called once the upstream sets a {@link Disposable} on this {@code ResourceObserver}.
111 *
112 * <p>You can perform initialization at this moment. The default
113 * implementation does nothing.
114 */
115 protected void onStart() {
116 }
117
118 /**
119 * Cancels the main disposable (if any) and disposes the resources associated with
120 * this {@code ResourceObserver} (if any).
121 *
122 * <p>This method can be called before the upstream calls {@link #onSubscribe(Disposable)} at which
123 * case the main {@link Disposable} will be immediately disposed.
124 */
125 @Override
126 public final void dispose() {
127 if (DisposableHelper.dispose(upstream)) {
128 resources.dispose();
129 }
130 }
131
132 /**
133 * Returns true if this {@code ResourceObserver} has been disposed/cancelled.
134 * @return true if this {@code ResourceObserver} has been disposed/cancelled
135 */
136 @Override
137 public final boolean isDisposed() {
138 return DisposableHelper.isDisposed(upstream.get());
139 }
140 }