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

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

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

Observable.singleOrDefault介绍

[英]Returns an Observable that emits the single item emitted by the source Observable, if that Observable emits only a single item, or a default item if the source Observable emits no items. If the source Observable emits more than one item, throw an IllegalArgumentException.

Scheduler: singleOrDefault does not operate by default on a particular Scheduler.
[中]如果源可观测对象仅发射单个项,则返回发射源可观测对象发射的单个项的可观测对象;如果源可观测对象未发射任何项,则返回默认项。如果源Observable发出多个项,则抛出IllegalArgumentException。
调度程序:默认情况下,singleOrDefault不会在特定调度程序上运行。

代码示例

代码示例来源:origin: jooby-project/jooby

@Override
public <T> Observable<List<T>> query(final N1qlQuery query) {
 return bucket.query(query)
   .flatMap(aqr -> Observable.zip(aqr.rows().toList(),
     aqr.errors().toList(),
     aqr.finalSuccess().singleOrDefault(Boolean.FALSE),
     (rows, errors, finalSuccess) -> {
      if (!finalSuccess) {
       throw new QueryExecutionException(
         "execution of query resulted in exception: ",
         Try.apply(() -> errors.get(0)).orElse(null));
      }
      List<T> value = new ArrayList<>();
      for (AsyncN1qlQueryRow row : rows) {
       try {
        T v = converter.fromBytes(row.byteValue());
        value.add(v);
       } catch (IOException ex) {
        throw new QueryExecutionException(
          "execution of query resulted in exception", null, ex);
       }
      }
      return value;
     }));
}

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

@Override
 public void run() {
  Observable.<Integer>empty().singleOrDefault(10).subscribe(new Action1<Integer>() {
   @Override
   public void call(Integer integer) {
    log(integer);
   }
  });
 }
});

代码示例来源:origin: alex-shpak/rx-jersey

@Override
  public Single convert(Observable<?> result) throws Throwable {
    return result.singleOrDefault(null).toSingle();
  }
}

代码示例来源:origin: com.netflix.rxjava/rxjava-core

/**
 * Returns an Observable that emits only the very first item emitted by the source Observable, or a default
 * item if the source Observable completes without emitting anything.
 * <p>
 * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefault.png" alt="">
 * <dl>
 *  <dt><b>Scheduler:</b></dt>
 *  <dd>{@code firstOrDefault} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 * 
 * @param defaultValue
 *            the default item to emit if the source Observable doesn't emit anything
 * @return an Observable that emits only the very first item from the source, or a default item if the
 *         source Observable completes without emitting any items
 * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#firstordefault">RxJava wiki: firstOrDefault</a>
 * @see "MSDN: Observable.firstOrDefaultAsync"
 */
public final Observable<T> firstOrDefault(T defaultValue) {
  return take(1).singleOrDefault(defaultValue);
}

代码示例来源:origin: com.netflix.rxjava/rxjava-core

/**
 * Returns an Observable that emits only the last item emitted by the source Observable, or a default item
 * if the source Observable completes without emitting any items.
 * <p>
 * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.png" alt="">
 * <dl>
 *  <dt><b>Scheduler:</b></dt>
 *  <dd>{@code lastOrDefault} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 * 
 * @param defaultValue
 *            the default item to emit if the source Observable is empty
 * @return an Observable that emits only the last item emitted by the source Observable, or a default item
 *         if the source Observable is empty
 * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#lastordefault">RxJava wiki: lastOrDefault</a>
 * @see "MSDN: Observable.lastOrDefaultAsync"
 */
public final Observable<T> lastOrDefault(T defaultValue) {
  return takeLast(1).singleOrDefault(defaultValue);
}

代码示例来源:origin: com.netflix.rxjava/rxjava-core

/**
 * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies
 * a specified condition, or a default item if the source Observable emits no such items.
 * <p>
 * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefaultN.png" alt="">
 * <dl>
 *  <dt><b>Scheduler:</b></dt>
 *  <dd>{@code firstOrDefault} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 * 
 * @param predicate
 *            the condition any item emitted by the source Observable has to satisfy
 * @param defaultValue
 *            the default item to emit if the source Observable doesn't emit anything that satisfies the
 *            {@code predicate}
 * @return an Observable that emits only the very first item emitted by the source Observable that satisfies
 *         the {@code predicate}, or a default item if the source Observable emits no such items
 * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#firstordefault">RxJava wiki: firstOrDefault</a>
 * @see "MSDN: Observable.firstOrDefaultAsync"
 */
public final Observable<T> firstOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
  return takeFirst(predicate).singleOrDefault(defaultValue);
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public DesignDocument getDesignDocument(final String name, final long timeout, final TimeUnit timeUnit) {
  return Blocking.blockForSingle(
    asyncBucketManager.getDesignDocument(name).singleOrDefault(null), timeout, timeUnit
  );
}

代码示例来源:origin: com.netflix.rxjava/rxjava-core

/**
 * If this {@code BlockingObservable} completes after emitting a single item that matches a predicate,
 * return that item; if it emits more than one such item, throw an {@code IllegalArgumentException}; if it
 * emits no items, return a default value.
 * <p>
 * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/B.singleOrDefault.p.png" alt="">
 *
 * @param defaultValue
 *            a default value to return if this {@code BlockingObservable} emits no matching items
 * @param predicate
 *            a predicate function to evaluate items emitted by this {@code BlockingObservable}
 * @return the single item emitted by the {@code BlockingObservable} that matches the predicate, or the
 *         default value if no such items are emitted
 * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators#single-and-singleordefault">RxJava Wiki: singleOrDefault()</a>
 * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.singleordefault.aspx">MSDN: Observable.SingleOrDefault</a>
 */
public T singleOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) {
  return blockForSingle(o.filter(predicate).map(Functions.<T>identity()).singleOrDefault(defaultValue));
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public DesignDocument getDesignDocument(final String name, final boolean development, final long timeout,
  final TimeUnit timeUnit) {
  return Blocking.blockForSingle(
    asyncBucketManager.getDesignDocument(name, development).singleOrDefault(null), timeout, timeUnit
  );
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public BucketSettings getBucket(String name, long timeout, TimeUnit timeUnit) {
  return Blocking.blockForSingle(asyncClusterManager.getBucket(name).singleOrDefault(null), timeout, timeUnit);
}

代码示例来源:origin: com.netflix.rxjava/rxjava-core

/**
 * If this {@code BlockingObservable} completes after emitting a single item, return that item; if it emits
 * more than one item, throw an {@code IllegalArgumentException}; if it emits no items, return a default
 * value.
 * <p>
 * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/B.singleOrDefault.png" alt="">
 *
 * @param defaultValue
 *            a default value to return if this {@code BlockingObservable} emits no items
 * @return the single item emitted by this {@code BlockingObservable}, or the default value if it emits no
 *         items
 * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators#single-and-singleordefault">RxJava Wiki: singleOrDefault()</a>
 * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.singleordefault.aspx">MSDN: Observable.SingleOrDefault</a>
 */
public T singleOrDefault(T defaultValue) {
  return blockForSingle(o.map(Functions.<T>identity()).singleOrDefault(defaultValue));
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public JsonDocument document(long timeout, TimeUnit timeUnit) {
  return Blocking.blockForSingle(asyncViewRow.document().singleOrDefault(null), timeout, timeUnit);
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public <D extends Document<?>> D document(Class<D> target, long timeout, TimeUnit timeUnit) {
  return Blocking.blockForSingle(asyncViewRow.document(target).singleOrDefault(null), timeout, timeUnit);
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public JsonDocument document(long timeout, TimeUnit timeUnit) {
  return Blocking.blockForSingle(asyncViewRow.document().singleOrDefault(null), timeout, timeUnit);
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public <D extends Document<?>> D document(Class<D> target, long timeout, TimeUnit timeUnit) {
  return Blocking.blockForSingle(asyncViewRow.document(target).singleOrDefault(null), timeout, timeUnit);
}

代码示例来源:origin: com.couchbase.client/java-client

/**
 * Maps a raw {@link ViewQueryResponse} into a {@link AsyncViewResult}.
 *
 * @param bucket reference to the bucket.
 * @param query the original query object.
 * @param response the response from the server.
 * @return a converted {@link AsyncViewResult}.
 */
public static Observable<AsyncViewResult> mapToViewResult(final AsyncBucket bucket, final ViewQuery query,
  final ViewQueryResponse response) {
  return response
    .info()
    .singleOrDefault(null)
    .map(new ByteBufToJsonObject())
    .map(new BuildViewResult(bucket, query, response));
}

代码示例来源:origin: com.couchbase.client/java-client

/**
 * Maps a raw {@link ViewQueryResponse} into a {@link AsyncSpatialViewResult}.
 *
 * @param bucket reference to the bucket.
 * @param query the original query object.
 * @param response the response from the server.
 * @return a converted {@link AsyncSpatialViewResult}.
 */
public static Observable<AsyncSpatialViewResult> mapToSpatialViewResult(final AsyncBucket bucket,
  final SpatialViewQuery query, final ViewQueryResponse response) {
  return response
    .info()
    .singleOrDefault(null)
    .map(new ByteBufToJsonObject())
    .map(new BuildSpatialViewResult(bucket, query, response));
}

代码示例来源: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: com.couchbase.client/java-client

@Override
  public Observable<AnalyticsQueryResult> call(final AsyncAnalyticsQueryResult aqr) {
    final boolean parseSuccess = aqr.parseSuccess();
    final String requestId = aqr.requestId();
    final String clientContextId = aqr.clientContextId();
    return Observable.zip(aqr.signature().singleOrDefault(JsonObject.empty()),
        aqr.info().singleOrDefault(AnalyticsMetrics.EMPTY_METRICS),
        aqr.errors().toList(),
        aqr.status(),
        aqr.finalSuccess().singleOrDefault(Boolean.FALSE),
        new Func5<Object, AnalyticsMetrics, List<JsonObject>, String, Boolean, AnalyticsQueryResult>() {
          @Override
          public AnalyticsQueryResult call(Object signature, AnalyticsMetrics info, List<JsonObject> errors, String finalStatus, Boolean finalSuccess) {
            return new DefaultAnalyticsQueryResult(aqr.handle(), signature, info, errors, finalStatus, finalSuccess,
                parseSuccess, requestId, clientContextId);
          }
        });
  }
};

代码示例来源:origin: com.couchbase.client/java-client

@Override
  public Observable<AnalyticsQueryResult> call(AsyncAnalyticsQueryResult aqr) {
    final boolean parseSuccess = aqr.parseSuccess();
    final String requestId = aqr.requestId();
    final String clientContextId = aqr.clientContextId();
    return Observable.zip(aqr.rows().toList(),
      aqr.signature().singleOrDefault(JsonObject.empty()),
      aqr.info().singleOrDefault(AnalyticsMetrics.EMPTY_METRICS),
      aqr.errors().toList(),
      aqr.status(),
      aqr.finalSuccess().singleOrDefault(Boolean.FALSE),
      new Func6<List<AsyncAnalyticsQueryRow>, Object, AnalyticsMetrics, List<JsonObject>, String, Boolean, AnalyticsQueryResult>() {
        @Override
        public AnalyticsQueryResult call(List<AsyncAnalyticsQueryRow> rows, Object signature,
          AnalyticsMetrics info, List<JsonObject> errors, String finalStatus, Boolean finalSuccess) {
          return new DefaultAnalyticsQueryResult(rows, signature, info, errors, finalStatus, finalSuccess,
            parseSuccess, requestId, clientContextId);
        }
      });
  }
};

相关文章

Observable类方法