Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableLastMaybe.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.flowable;
15
16 import org.reactivestreams.*;
17
18 import io.reactivex.rxjava3.core.*;
19 import io.reactivex.rxjava3.disposables.Disposable;
20 import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
21
22 /**
23 * Consumes the source Publisher and emits its last item or completes.
24 *
25 * @param <T> the value type
26 */
27 public final class FlowableLastMaybe<T> extends Maybe<T> {
28
29 final Publisher<T> source;
30
31 public FlowableLastMaybe(Publisher<T> source) {
32 this.source = source;
33 }
34
35 // TODO fuse back to Flowable
36
37 @Override
38 protected void subscribeActual(MaybeObserver<? super T> observer) {
39 source.subscribe(new LastSubscriber<>(observer));
40 }
41
42 static final class LastSubscriber<T> implements FlowableSubscriber<T>, Disposable {
43
44 final MaybeObserver<? super T> downstream;
45
46 Subscription upstream;
47
48 T item;
49
50 LastSubscriber(MaybeObserver<? super T> downstream) {
51 this.downstream = downstream;
52 }
53
54 @Override
55 public void dispose() {
56 upstream.cancel();
57 upstream = SubscriptionHelper.CANCELLED;
58 }
59
60 @Override
61 public boolean isDisposed() {
62 return upstream == SubscriptionHelper.CANCELLED;
63 }
64
65 @Override
66 public void onSubscribe(Subscription s) {
67 if (SubscriptionHelper.validate(this.upstream, s)) {
68 this.upstream = s;
69
70 downstream.onSubscribe(this);
71
72 s.request(Long.MAX_VALUE);
73 }
74 }
75
76 @Override
77 public void onNext(T t) {
78 item = t;
79 }
80
81 @Override
82 public void onError(Throwable t) {
83 upstream = SubscriptionHelper.CANCELLED;
84 item = null;
85 downstream.onError(t);
86 }
87
88 @Override
89 public void onComplete() {
90 upstream = SubscriptionHelper.CANCELLED;
91 T v = item;
92 if (v != null) {
93 item = null;
94 downstream.onSuccess(v);
95 } else {
96 downstream.onComplete();
97 }
98 }
99 }
100 }