| 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 io.reactivex.rxjava3.annotations.NonNull; |
| 17 |
import io.reactivex.rxjava3.core.CompletableObserver; |
| 18 |
import io.reactivex.rxjava3.disposables.Disposable; |
| 19 |
import io.reactivex.rxjava3.exceptions.*; |
| 20 |
import io.reactivex.rxjava3.plugins.RxJavaPlugins; |
| 21 |
|
| 22 |
/** |
| 23 |
* Wraps another {@link CompletableObserver} and catches exceptions thrown by its |
| 24 |
* {@code onSubscribe}, {@code onError} or |
| 25 |
* {@code onComplete} methods despite the protocol forbids it. |
| 26 |
* <p> |
| 27 |
* Such exceptions are routed to the {@link RxJavaPlugins#onError(Throwable)} handler. |
| 28 |
* |
| 29 |
* @since 3.0.0 |
| 30 |
*/ |
| 31 |
public final class SafeCompletableObserver implements CompletableObserver { |
| 32 |
|
| 33 |
final CompletableObserver downstream; |
| 34 |
|
| 35 |
boolean onSubscribeFailed; |
| 36 |
|
| 37 |
public SafeCompletableObserver(CompletableObserver downstream) { |
| 38 |
this.downstream = downstream; |
| 39 |
} |
| 40 |
|
| 41 |
@Override |
| 42 |
public void onSubscribe(@NonNull Disposable d) { |
| 43 |
try { |
| 44 |
downstream.onSubscribe(d); |
| 45 |
} catch (Throwable ex) { |
| 46 |
Exceptions.throwIfFatal(ex); |
| 47 |
onSubscribeFailed = true; |
| 48 |
d.dispose(); |
| 49 |
RxJavaPlugins.onError(ex); |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
@Override |
| 54 |
public void onError(@NonNull Throwable e) { |
| 55 |
if (onSubscribeFailed) { |
| 56 |
RxJavaPlugins.onError(e); |
| 57 |
} else { |
| 58 |
try { |
| 59 |
downstream.onError(e); |
| 60 |
} catch (Throwable ex) { |
| 61 |
Exceptions.throwIfFatal(ex); |
| 62 |
RxJavaPlugins.onError(new CompositeException(e, ex)); |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
@Override |
| 68 |
public void onComplete() { |
| 69 |
if (!onSubscribeFailed) { |
| 70 |
try { |
| 71 |
downstream.onComplete(); |
| 72 |
} catch (Throwable ex) { |
| 73 |
Exceptions.throwIfFatal(ex); |
| 74 |
RxJavaPlugins.onError(ex); |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
} |