rx.Observable.onErrorReturn()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(8.3k)|赞(0)|评价(0)|浏览(165)

本文整理了Java中rx.Observable.onErrorReturn()方法的一些代码示例,展示了Observable.onErrorReturn()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Observable.onErrorReturn()方法的具体详情如下:
包路径:rx.Observable
类名称:Observable
方法名:onErrorReturn

Observable.onErrorReturn介绍

[英]Instructs an Observable to emit an item (returned by a specified function) rather than invoking Observer#onError if it encounters an error.

By default, when an Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable 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 Observable's onErrorReturnmethod, if the original Observable 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.
[中]指示可观察对象发出项目(由指定函数返回),而不是在遇到错误时调用Observer#onError。
默认情况下,当一个可观察对象遇到一个错误,阻止它向其观察者发送预期的项目时,该可观察对象调用其观察者的onError方法,然后退出,不再调用任何观察者的方法。OneRorReturn方法会更改此行为。如果将函数(resumeFunction)传递给观察者的OneRorReturnMethod,如果原始观察者遇到错误,它不会调用观察者的OneRor方法,而是会发出resumeFunction的返回值。
您可以使用它来防止错误传播,或者在遇到错误时提供回退数据。Scheduler:onErrorReturn默认情况下不会在特定的计划程序上运行。

代码示例

代码示例来源:origin: hidroh/materialistic

@Override
public void send(String title, String body, final Callback callback) {
  body = String.format("%s\nDevice: %s %s, SDK: %s, app version: %s",
      body,
      Build.MANUFACTURER,
      Build.MODEL,
      Build.VERSION.SDK_INT,
      BuildConfig.VERSION_CODE);
  mFeedbackService.createGithubIssue(new Issue(title, body))
      .map(response -> true)
      .onErrorReturn(throwable -> false)
      .observeOn(mMainThreadScheduler)
      .subscribe(callback::onSent);
}

代码示例来源:origin: hidroh/materialistic

public static void init(Context context, Scheduler scheduler) {
  Observable.fromCallable(() -> loadFromAssets(context))
      .onErrorReturn(throwable -> null)
      .subscribeOn(scheduler)
      .subscribe();
}

代码示例来源:origin: hidroh/materialistic

@NonNull
private Observable<String> fromNetwork(String itemId, String url) {
  return mMercuryService.parse(url)
      .onErrorReturn(throwable -> null)
      .map(readable -> readable == null ? null : readable.content)
      .doOnNext(content -> mCache.putReadability(itemId, content));
}

代码示例来源:origin: jhusain/learnrxjava

}).onErrorReturn(throwable -> {
  return "fallback value";
}).subscribe(System.out::println);

代码示例来源:origin: com.squareup.retrofit/adapter-rxjava

@Override public <R> Observable<Result<R>> adapt(Call<R> call) {
  return Observable.create(new CallOnSubscribe<>(call)) //
    .map(new Func1<Response<R>, Result<R>>() {
     @Override public Result<R> call(Response<R> response) {
      return Result.response(response);
     }
    })
    .onErrorReturn(new Func1<Throwable, Result<R>>() {
     @Override public Result<R> call(Throwable throwable) {
      return Result.error(throwable);
     }
    });
 }
}

代码示例来源:origin: ojacquemart/spring-boot-rxjava

private Observable<RawUser[]> getFollowersObservable(String login) {
  return Observable.create((Subscriber<? super RawUser[]> s) -> s.onNext(restClient.getFollowers(login)))
      .onErrorReturn(throwable -> {
        log.error("Failed to retrieve {} followers", login, throwable);
        return new RawUser[]{};
      })
      .subscribeOn(Schedulers.computation());
}

代码示例来源:origin: ojacquemart/spring-boot-rxjava

private Observable<Repository[]> getReposObservable(String login) {
  return Observable.create((Subscriber<? super Repository[]> s) -> s.onNext(restClient.getRepositories(login)))
      .onErrorReturn(throwable -> {
        log.error("Failed to retrieve {} repos", login, throwable);
        return new Repository[]{};
      })
      .subscribeOn(Schedulers.computation());
}

代码示例来源:origin: ojacquemart/spring-boot-rxjava

private Observable<RawUser> getRawUserObservable(String login) {
  return Observable.create((Subscriber<? super RawUser> s) -> s.onNext(restClient.getUser(login)))
      .onErrorReturn(throwable -> {
        log.error("Failed to retrieve user {}", login, throwable);
        return new RawUser("???", null, null);
      })
      .subscribeOn(Schedulers.computation());
}

代码示例来源: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: twinformatics/eureka-consul-adapter

public Observable<Long> getTotalIndex(long millis) {
  // waits for change or x seconds
  return eventStream
      .timeout(millis, TimeUnit.MILLISECONDS)
      .onErrorReturn(err -> mapTimeoutToServiceChange(err, ""))
      .map(se -> getLastEmitted());
}

代码示例来源:origin: Petikoch/Java_MVVM_with_Swing_and_RxJava_Examples

@Override
public void connectTo(final Example_7a_Model model) {
  model.getLogs()
      .doOnError(throwable -> vm2v_log.onNext(new LogRow("!", "Unexpected error -> will retry here in ViewModel", "Error: " + throwable.getMessage())))
      .retry(5)
      .onErrorReturn(throwable -> new LogRow("!!!", "Too many unexpected errors -> stop", "Error: " + throwable.getMessage()))
      .subscribe(vm2v_log);
}

代码示例来源:origin: bijukunjummen/sample-spring-hystrix

public static <T> Observable<T> executeObservable(String groupKey, String commandkey, Supplier<T> toRun, Function<Throwable, T> fallback) {
  return new GenericHystrixCommand<>(groupKey, commandkey, toRun, fallback)
      .toObservable()
      .onErrorReturn(t -> {throw wrappedException(t);});
}

代码示例来源:origin: VictorAlbertos/RxGcm

public Observable<Boolean> sendGcmNotificationRequestingSupply(String title, String body) {
  return RxGcm.Notifications.currentToken()
      .map(token -> new Payload(token, title, body, TARGET_SUPPLY_GCM))
      .concatMap(payload -> apiGcmServer.sendNotification(payload))
      .map(gcmResponseServerResponse -> gcmResponseServerResponse.body().success())
      .onErrorReturn(throwable -> false);
}

代码示例来源:origin: VictorAlbertos/RxGcm

public Observable<Boolean> sendGcmNotificationRequestingIssue(String title, String body) {
  return RxGcm.Notifications.currentToken()
      .map(token -> new Payload(token, title, body, TARGET_ISSUE_GCM))
      .concatMap(payload -> apiGcmServer.sendNotification(payload))
      .map(gcmResponseServerResponse -> gcmResponseServerResponse.body().success())
      .onErrorReturn(throwable -> false);
}

代码示例来源:origin: VictorAlbertos/RxGcm

public Observable<Boolean> sendGcmNotificationRequestingNestedSupply(String title, String body) {
  return RxGcm.Notifications.currentToken()
      .map(token -> new Payload(token, title, body, TARGET_NESTED_SUPPLY_GCM))
      .concatMap(payload -> apiGcmServer.sendNotification(payload))
      .map(gcmResponseServerResponse -> gcmResponseServerResponse.body().success())
      .onErrorReturn(throwable -> false);
}

代码示例来源:origin: twinformatics/eureka-consul-adapter

public Observable<Long> getIndexOfApp(String appName, long millis) {
  // waits for change of app A or x seconds
  return eventStream
      .filter(se -> se.getName().equals(appName))
      .timeout(millis, TimeUnit.MILLISECONDS)
      .onErrorReturn(err -> mapTimeoutToServiceChange(err, appName))
      .map(se -> getLastEmittedOfApp(se.getName()));
}

代码示例来源:origin: nurkiewicz/rxjava-book-examples

@Test
public void sample_291() throws Exception {
  Observable<String> obs = Observable
      .<String>error(new RuntimeException("Swallowed"))
      .doOnError(th -> log.warn("onError", th))
      .onErrorReturn(th -> "Fallback");
}

代码示例来源:origin: nurkiewicz/rxjava-book-examples

default Observable<Integer> populationOf(String query) {
  return search(query)
      .concatMapIterable(SearchResult::getGeonames)
      .map(Geoname::getPopulation)
      .filter(p -> p != null)
      .singleOrDefault(0)
      .doOnError(th ->
          log.warn("Falling back to 0 for {}", query, th))
      .onErrorReturn(th -> 0)
      .subscribeOn(Schedulers.io());
}

代码示例来源:origin: nurkiewicz/rxjava-book-examples

@Test
public void sample_129() throws Exception {
  Observable<Person> person = Observable.just(new Person());
  Observable<Income> income = person
      .flatMap(this::determineIncome)
      .onErrorReturn(error -> Income.no());
}

代码示例来源:origin: nurkiewicz/rxjava-book-examples

@Test
public void sample_177() throws Exception {
  List<Ticket> tickets = Arrays.asList(new Ticket(), new Ticket(), new Ticket());
  List<Ticket> failures = Observable.from(tickets)
      .flatMap(ticket ->
          rxSendEmail(ticket)
              .flatMap(response -> Observable.<Ticket>empty())
              .doOnError(e -> log.warn("Failed to send {}", ticket, e))
              .onErrorReturn(err -> ticket))
      .toList()
      .toBlocking()
      .single();
}

相关文章

Observable类方法