本文整理了Java中io.reactivex.Observable.onErrorReturn()
方法的一些代码示例,展示了Observable.onErrorReturn()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Observable.onErrorReturn()
方法的具体详情如下:
包路径:io.reactivex.Observable
类名称:Observable
方法名:onErrorReturn
[英]Instructs an ObservableSource to emit an item (returned by a specified function) rather than invoking Observer#onError if it encounters an error.
By default, when an ObservableSource encounters an error that prevents it from emitting the expected item to its Observer, the ObservableSource invokes its Observer's onError method, and then quits without invoking any more of its Observer's methods. The onErrorReturn method changes this behavior. If you pass a function ( resumeFunction) to an ObservableSource's onErrorReturnmethod, if the original ObservableSource encounters an error, instead of invoking its Observer's onError method, it will instead emit the return value of resumeFunction.
You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. Scheduler: onErrorReturn does not operate by default on a particular Scheduler.
[中]指示ObservateSource发出一个项(由指定函数返回),而不是在遇到错误时调用Observator#onError。
默认情况下,当ObservateSource遇到一个错误,阻止它向其观察者发送预期的项时,ObservateSource调用其观察者的OneError方法,然后退出,不再调用任何观察者的方法。OneRorReturn方法会更改此行为。如果将函数(resumeFunction)传递给ObservateSource的onErrorReturnmethod,如果原始ObservateSource遇到错误,它将不会调用其Observater的onError方法,而是发出resumeFunction的返回值。
您可以使用它来防止错误传播,或者在遇到错误时提供回退数据。Scheduler:onErrorReturn默认情况下不会在特定的计划程序上运行。
代码示例来源:origin: ReactiveX/RxJava
@Test(expected = NullPointerException.class)
public void onErrorReturnFunctionNull() {
just1.onErrorReturn(null);
}
代码示例来源:origin: Polidea/RxAndroidBle
/**
* A convenience function creating a transformer that will wrap the emissions in either {@link ResultEvent} or {@link ErrorEvent}
* with a given {@link Type}
*
* @param type the type to wrap with
* @return transformer that will emit an observable that will be emitting ResultEvent or ErrorEvent with a given type
*/
@NonNull
private static ObservableTransformer<byte[], PresenterEvent> transformToPresenterEvent(Type type) {
return observable -> observable.map(writtenBytes -> ((PresenterEvent) new ResultEvent(writtenBytes, type)))
.onErrorReturn(throwable -> new ErrorEvent(throwable, type));
}
代码示例来源:origin: Polidea/RxAndroidBle
/**
* A convenience function creating a transformer that will wrap the emissions in either {@link ResultEvent} or {@link ErrorEvent}
* with a given {@link Type} for notification type {@link Observable} (Observable<Observable<byte[]>>)
*
* @param type the type to wrap with
* @return the transformer
*/
@NonNull
private static ObservableTransformer<Observable<byte[]>, PresenterEvent> transformToNotificationPresenterEvent(Type type) {
return observableObservable -> observableObservable
.flatMap(observable -> observable
.map(bytes -> ((PresenterEvent) new ResultEvent(bytes, type)))
)
.onErrorReturn(throwable -> new ErrorEvent(throwable, type));
}
代码示例来源:origin: trello/RxLifecycle
private static <R> Observable<Boolean> takeUntilCorrespondingEvent(final Observable<R> lifecycle,
final Function<R, R> correspondingEvents) {
return Observable.combineLatest(
lifecycle.take(1).map(correspondingEvents),
lifecycle.skip(1),
new BiFunction<R, R, Boolean>() {
@Override
public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception {
return lifecycleEvent.equals(bindUntilEvent);
}
})
.onErrorReturn(Functions.RESUME_FUNCTION)
.filter(Functions.SHOULD_COMPLETE);
}
}
代码示例来源:origin: ReactiveX/RxJava
public final Observable<T> onErrorReturnItem(final T item) {
ObjectHelper.requireNonNull(item, "item is null");
return onErrorReturn(Functions.justFunction(item));
代码示例来源:origin: ReactiveX/RxJava
@Test
public void testResumeNext() {
TestObservable f = new TestObservable("one");
Observable<String> w = Observable.unsafeCreate(f);
final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>();
Observable<String> observable = w.onErrorReturn(new Function<Throwable, String>() {
@Override
public String apply(Throwable e) {
capturedException.set(e);
return "failure";
}
});
Observer<String> observer = TestHelper.mockObserver();
observable.subscribe(observer);
try {
f.t.join();
} catch (InterruptedException e) {
fail(e.getMessage());
}
verify(observer, Mockito.never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
verify(observer, times(1)).onNext("one");
verify(observer, times(1)).onNext("failure");
assertNotNull(capturedException.get());
}
代码示例来源:origin: ReactiveX/RxJava
/**
* Test that when a function throws an exception this is propagated through onError.
*/
@Test
public void testFunctionThrowsError() {
TestObservable f = new TestObservable("one");
Observable<String> w = Observable.unsafeCreate(f);
final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>();
Observable<String> observable = w.onErrorReturn(new Function<Throwable, String>() {
@Override
public String apply(Throwable e) {
capturedException.set(e);
throw new RuntimeException("exception from function");
}
});
Observer<String> observer = TestHelper.mockObserver();
observable.subscribe(observer);
try {
f.t.join();
} catch (InterruptedException e) {
fail(e.getMessage());
}
// we should get the "one" value before the error
verify(observer, times(1)).onNext("one");
// we should have received an onError call on the Observer since the resume function threw an exception
verify(observer, times(1)).onError(any(Throwable.class));
verify(observer, times(0)).onComplete();
assertNotNull(capturedException.get());
}
代码示例来源:origin: ReactiveX/RxJava
Observable<String> observable = w.onErrorReturn(new Function<Throwable, String>() {
代码示例来源:origin: ReactiveX/RxJava
@Test
public void testBackpressure() {
TestObserver<Integer> to = new TestObserver<Integer>();
Observable.range(0, 100000)
.onErrorReturn(new Function<Throwable, Integer>() {
@Override
public Integer apply(Throwable t1) {
return 1;
}
})
.observeOn(Schedulers.computation())
.map(new Function<Integer, Integer>() {
int c;
@Override
public Integer apply(Integer t1) {
if (c++ <= 1) {
// slow
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return t1;
}
})
.subscribe(to);
to.awaitTerminalEvent();
to.assertNoErrors();
}
代码示例来源:origin: ReactiveX/RxJava
@Test(expected = NullPointerException.class)
public void onErrorReturnFunctionReturnsNull() {
Observable.error(new TestException()).onErrorReturn(new Function<Throwable, Object>() {
@Override
public Object apply(Throwable e) {
return null;
}
}).blockingSubscribe();
}
代码示例来源:origin: redisson/redisson
public final Observable<T> onErrorReturnItem(final T item) {
ObjectHelper.requireNonNull(item, "item is null");
return onErrorReturn(Functions.justFunction(item));
代码示例来源:origin: Polidea/RxAndroidBle
.onErrorReturn(throwable -> new InfoEvent("Connection error: " + throwable))
代码示例来源:origin: Marchuck/BlueDuff
private void openInputStream(BluetoothSocket bluetoothSocket) {
getInputStream(bluetoothSocket).map(new Function<InputStream, Boolean>() {
@Override
public Boolean apply(InputStream inputStream) throws Exception {
is = inputStream;
receiveMessages();
return true;
}
}).onErrorReturn(new Function<Throwable, Boolean>() {
@Override
public Boolean apply(Throwable throwable) throws Exception {
return false;
}
}).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean success) throws Exception {
if (!success) {
connectionCallbacks.onDisconnected();
}
}
});
}
代码示例来源:origin: Marchuck/BlueDuff
void openOutputStream(final BluetoothSocket bluetoothSocket) {
Observable.fromCallable(new Callable<OutputStream>() {
@Override
public OutputStream call() throws Exception {
return bluetoothSocket.getOutputStream();
}
}).map(new Function<OutputStream, Boolean>() {
@Override
public Boolean apply(OutputStream outputStream) throws Exception {
os = outputStream;
return true;
}
}).onErrorReturn(new Function<Throwable, Boolean>() {
@Override
public Boolean apply(Throwable throwable) throws Exception {
return false;
}
}).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean canWrite) throws Exception {
if (!canWrite) connectionCallbacks.onError("Cannot send data");
}
});
}
代码示例来源:origin: WallaceXiao/StockChart-MPAndroidChart
@Override
public ObservableSource<CacheResult<T>> apply(final @NonNull T t) throws Exception {
return rxCache.save(key, t).map(new Function<Boolean, CacheResult<T>>() {
@Override
public CacheResult<T> apply(@NonNull Boolean aBoolean) throws Exception {
HttpLog.i("save status => " + aBoolean);
return new CacheResult<T>(false, t);
}
}).onErrorReturn(new Function<Throwable, CacheResult<T>>() {
@Override
public CacheResult<T> apply(@NonNull Throwable throwable) throws Exception {
HttpLog.i("save status => " + throwable);
return new CacheResult<T>(false, t);
}
});
}
});
代码示例来源:origin: groupon/grox
@Override
public Observable<? extends Action<State>> actions() {
final Observable<Action<State>> refresh = just(new RefreshAction());
//don't forget to convert errors in actions
return refresh.concatWith(refreshColor()).onErrorReturn(ErrorAction::new);
}
代码示例来源:origin: VictorAlbertos/RxCacheSamples
public Observable<String> logoutUser() {
return cacheProviders.getCurrentUser(ProviderHelper.<User>withoutLoader(), new EvictProvider(true))
.map(new Function<Reply<User>, String>() {
@Override public String apply(Reply<User> user) throws Exception {
return "Logout";
}
})
.onErrorReturn(new Function<Throwable, String>() {
@Override public String apply(Throwable throwable) {
return "Logout";
}
});
}
代码示例来源:origin: com.trello.rxlifecycle3/rxlifecycle
private static <R> Observable<Boolean> takeUntilCorrespondingEvent(final Observable<R> lifecycle,
final Function<R, R> correspondingEvents) {
return Observable.combineLatest(
lifecycle.take(1).map(correspondingEvents),
lifecycle.skip(1),
new BiFunction<R, R, Boolean>() {
@Override
public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception {
return lifecycleEvent.equals(bindUntilEvent);
}
})
.onErrorReturn(Functions.RESUME_FUNCTION)
.filter(Functions.SHOULD_COMPLETE);
}
}
代码示例来源:origin: com.trello.rxlifecycle2/rxlifecycle
private static <R> Observable<Boolean> takeUntilCorrespondingEvent(final Observable<R> lifecycle,
final Function<R, R> correspondingEvents) {
return Observable.combineLatest(
lifecycle.take(1).map(correspondingEvents),
lifecycle.skip(1),
new BiFunction<R, R, Boolean>() {
@Override
public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception {
return lifecycleEvent.equals(bindUntilEvent);
}
})
.onErrorReturn(Functions.RESUME_FUNCTION)
.filter(Functions.SHOULD_COMPLETE);
}
}
代码示例来源:origin: cn.leancloud/storage-core
result = wrapObservable(QueryResultCache.getInstance().getCacheResult(className, query, maxAgeInMilliseconds, false));
if (null != result) {
result = result.onErrorReturn(new Function<Throwable, List<AVObject>>() {
public List<AVObject> apply(Throwable o) throws Exception {
LOGGER.d("failed to query local cache, cause: " + o.getMessage() + ", try to query networking");
return o.getResults();
}).onErrorReturn(new Function<Throwable, List<AVObject>>() {
public List<AVObject> apply(Throwable o) throws Exception {
LOGGER.d("failed to query networking, cause: " + o.getMessage() + ", try to query local cache.");
内容来源于网络,如有侵权,请联系作者删除!