Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/observers/BlockingBaseObserver.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.observers;
15
16 import java.util.concurrent.CountDownLatch;
17
18 import io.reactivex.rxjava3.core.Observer;
19 import io.reactivex.rxjava3.disposables.Disposable;
20 import io.reactivex.rxjava3.internal.util.*;
21
22 public abstract class BlockingBaseObserver<T> extends CountDownLatch
23 implements Observer<T>, Disposable {
24
25 T value;
26 Throwable error;
27
28 Disposable upstream;
29
30 volatile boolean cancelled;
31
32 public BlockingBaseObserver() {
33 super(1);
34 }
35
36 @Override
37 public final void onSubscribe(Disposable d) {
38 this.upstream = d;
39 if (cancelled) {
40 d.dispose();
41 }
42 }
43
44 @Override
45 public final void onComplete() {
46 countDown();
47 }
48
49 @Override
50 public final void dispose() {
51 cancelled = true;
52 Disposable d = this.upstream;
53 if (d != null) {
54 d.dispose();
55 }
56 }
57
58 @Override
59 public final boolean isDisposed() {
60 return cancelled;
61 }
62
63 /**
64 * Block until the first value arrives and return it, otherwise
65 * return null for an empty source and rethrow any exception.
66 * @return the first value or null if the source is empty
67 */
68 public final T blockingGet() {
69 if (getCount() != 0) {
70 try {
71 BlockingHelper.verifyNonBlocking();
72 await();
73 } catch (InterruptedException ex) {
74 dispose();
75 throw ExceptionHelper.wrapOrThrow(ex);
76 }
77 }
78
79 Throwable e = error;
80 if (e != null) {
81 throw ExceptionHelper.wrapOrThrow(e);
82 }
83 return value;
84 }
85 }