| 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.internal.subscriptions.SubscriptionArbiter; |
| 20 |
|
| 21 |
public final class FlowableSwitchIfEmpty<T> extends AbstractFlowableWithUpstream<T, T> { |
| 22 |
final Publisher<? extends T> other; |
| 23 |
public FlowableSwitchIfEmpty(Flowable<T> source, Publisher<? extends T> other) { |
| 24 |
super(source); |
| 25 |
this.other = other; |
| 26 |
} |
| 27 |
|
| 28 |
@Override |
| 29 |
protected void subscribeActual(Subscriber<? super T> s) { |
| 30 |
SwitchIfEmptySubscriber<T> parent = new SwitchIfEmptySubscriber<>(s, other); |
| 31 |
s.onSubscribe(parent.arbiter); |
| 32 |
source.subscribe(parent); |
| 33 |
} |
| 34 |
|
| 35 |
static final class SwitchIfEmptySubscriber<T> implements FlowableSubscriber<T> { |
| 36 |
final Subscriber<? super T> downstream; |
| 37 |
final Publisher<? extends T> other; |
| 38 |
final SubscriptionArbiter arbiter; |
| 39 |
|
| 40 |
boolean empty; |
| 41 |
|
| 42 |
SwitchIfEmptySubscriber(Subscriber<? super T> actual, Publisher<? extends T> other) { |
| 43 |
this.downstream = actual; |
| 44 |
this.other = other; |
| 45 |
this.empty = true; |
| 46 |
this.arbiter = new SubscriptionArbiter(false); |
| 47 |
} |
| 48 |
|
| 49 |
@Override |
| 50 |
public void onSubscribe(Subscription s) { |
| 51 |
arbiter.setSubscription(s); |
| 52 |
} |
| 53 |
|
| 54 |
@Override |
| 55 |
public void onNext(T t) { |
| 56 |
if (empty) { |
| 57 |
empty = false; |
| 58 |
} |
| 59 |
downstream.onNext(t); |
| 60 |
} |
| 61 |
|
| 62 |
@Override |
| 63 |
public void onError(Throwable t) { |
| 64 |
downstream.onError(t); |
| 65 |
} |
| 66 |
|
| 67 |
@Override |
| 68 |
public void onComplete() { |
| 69 |
if (empty) { |
| 70 |
empty = false; |
| 71 |
other.subscribe(this); |
| 72 |
} else { |
| 73 |
downstream.onComplete(); |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
} |