Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLastSingle.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.observable;
15
16 import java.util.NoSuchElementException;
17
18 import io.reactivex.rxjava3.core.*;
19 import io.reactivex.rxjava3.disposables.Disposable;
20 import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
21
22 /**
23 * Consumes the source ObservableSource and emits its last item, the defaultItem
24 * if empty or a NoSuchElementException if even the defaultItem is null.
25 *
26 * @param <T> the value type
27 */
28 public final class ObservableLastSingle<T> extends Single<T> {
29
30 final ObservableSource<T> source;
31
32 final T defaultItem;
33
34 public ObservableLastSingle(ObservableSource<T> source, T defaultItem) {
35 this.source = source;
36 this.defaultItem = defaultItem;
37 }
38
39 // TODO fuse back to Observable
40
41 @Override
42 protected void subscribeActual(SingleObserver<? super T> observer) {
43 source.subscribe(new LastObserver<>(observer, defaultItem));
44 }
45
46 static final class LastObserver<T> implements Observer<T>, Disposable {
47
48 final SingleObserver<? super T> downstream;
49
50 final T defaultItem;
51
52 Disposable upstream;
53
54 T item;
55
56 LastObserver(SingleObserver<? super T> actual, T defaultItem) {
57 this.downstream = actual;
58 this.defaultItem = defaultItem;
59 }
60
61 @Override
62 public void dispose() {
63 upstream.dispose();
64 upstream = DisposableHelper.DISPOSED;
65 }
66
67 @Override
68 public boolean isDisposed() {
69 return upstream == DisposableHelper.DISPOSED;
70 }
71
72 @Override
73 public void onSubscribe(Disposable d) {
74 if (DisposableHelper.validate(this.upstream, d)) {
75 this.upstream = d;
76
77 downstream.onSubscribe(this);
78 }
79 }
80
81 @Override
82 public void onNext(T t) {
83 item = t;
84 }
85
86 @Override
87 public void onError(Throwable t) {
88 upstream = DisposableHelper.DISPOSED;
89 item = null;
90 downstream.onError(t);
91 }
92
93 @Override
94 public void onComplete() {
95 upstream = DisposableHelper.DISPOSED;
96 T v = item;
97 if (v != null) {
98 item = null;
99 downstream.onSuccess(v);
100 } else {
101 v = defaultItem;
102 if (v != null) {
103 downstream.onSuccess(v);
104 } else {
105 downstream.onError(new NoSuchElementException());
106 }
107 }
108 }
109 }
110 }