Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduce.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 io.reactivex.rxjava3.annotations.NonNull;
17 import io.reactivex.rxjava3.core.Flowable;
18 import io.reactivex.rxjava3.exceptions.Exceptions;
19 import io.reactivex.rxjava3.functions.BiFunction;
20 import org.reactivestreams.Subscriber;
21
22 import java.util.Objects;
23
24 public final class FlowableOnBackpressureReduce<T> extends AbstractFlowableWithUpstream<T, T> {
25
26 final BiFunction<T, T, T> reducer;
27
28 public FlowableOnBackpressureReduce(@NonNull Flowable<T> source, @NonNull BiFunction<T, T, T> reducer) {
29 super(source);
30 this.reducer = reducer;
31 }
32
33 @Override
34 protected void subscribeActual(@NonNull Subscriber<? super T> s) {
35 source.subscribe(new BackpressureReduceSubscriber<>(s, reducer));
36 }
37
38 static final class BackpressureReduceSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T, T> {
39
40 private static final long serialVersionUID = 821363947659780367L;
41
42 final BiFunction<T, T, T> reducer;
43
44 BackpressureReduceSubscriber(@NonNull Subscriber<? super T> downstream, @NonNull BiFunction<T, T, T> reducer) {
45 super(downstream);
46 this.reducer = reducer;
47 }
48
49 @Override
50 public void onNext(T t) {
51 T v = current.get();
52 if (v != null) {
53 v = current.getAndSet(null);
54 }
55 if (v == null) {
56 current.lazySet(t);
57 } else {
58 try {
59 current.lazySet(Objects.requireNonNull(reducer.apply(v, t), "The reducer returned a null value"));
60 } catch (Throwable ex) {
61 Exceptions.throwIfFatal(ex);
62 upstream.cancel();
63 onError(ex);
64 return;
65 }
66 }
67 drain();
68 }
69 }
70 }