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

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

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

Observable.switchIfEmpty介绍

暂无

代码示例

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

  1. @WorkerThread
  2. @Override
  3. public void parse(String itemId, String url) {
  4. Observable.defer(() -> fromCache(itemId))
  5. .subscribeOn(Schedulers.immediate())
  6. .switchIfEmpty(fromNetwork(itemId, url))
  7. .map(content -> AndroidUtils.TextUtils.equals(EMPTY_CONTENT, content) ? null : content)
  8. .observeOn(Schedulers.immediate())
  9. .subscribe();
  10. }

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

  1. /**
  2. * Get an entity/document by ID. The unique ID is constructed via
  3. * {@link N1Q#qualifyId(Class, Object)}.
  4. *
  5. * If the entity is found, a entity is returned. Otherwise a
  6. * {@link DocumentDoesNotExistException}.
  7. *
  8. * @param entityClass Entity class.
  9. * @param id Entity id.
  10. * @param mode Replica mode.
  11. * @param <T> Entity type.
  12. * @return An entity matching the id or an empty observable.
  13. */
  14. default <T> T getFromReplica(final Class<T> entityClass, final Object id,
  15. final ReplicaMode mode) throws DocumentDoesNotExistException {
  16. return async().getFromReplica(entityClass, id, mode)
  17. .switchIfEmpty(notFound(entityClass, id))
  18. .toBlocking().single();
  19. }

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

  1. /**
  2. * Get an entity/document by ID. The unique ID is constructed via
  3. * {@link N1Q#qualifyId(Class, Object)}.
  4. *
  5. * If the entity is found, a entity is returned. Otherwise a
  6. * {@link DocumentDoesNotExistException}.
  7. *
  8. * @param entityClass Entity class.
  9. * @param id Entity id.
  10. * @param <T> Entity type.
  11. * @return An entity matching the id or an empty observable.
  12. */
  13. default <T> T get(final Class<T> entityClass, final Object id)
  14. throws DocumentDoesNotExistException {
  15. return async().get(entityClass, id)
  16. .switchIfEmpty(notFound(entityClass, id))
  17. .toBlocking().single();
  18. }

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

  1. /**
  2. * Retrieve and touch an entity by its unique ID.
  3. *
  4. * If the entity is found, an entity is returned. Otherwise a
  5. * {@link DocumentDoesNotExistException}.
  6. *
  7. * This method works similar to {@link #get(Class, Object)}, but in addition it touches the
  8. * entity, which will reset its configured expiration time to the value provided.
  9. *
  10. * @param entityClass Entity class.
  11. * @param id id the unique ID of the entity.
  12. * @param expiry the new expiration time for the entity (in seconds).
  13. * @param <T> Entity type.
  14. * @return an {@link Observable} eventually containing the found {@link JsonDocument}.
  15. */
  16. default <T> T getAndTouch(final Class<T> entityClass, final Object id, final int expiry)
  17. throws DocumentDoesNotExistException {
  18. return async().getAndTouch(entityClass, id, expiry)
  19. .switchIfEmpty(notFound(entityClass, id))
  20. .toBlocking().single();
  21. }

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

  1. /**
  2. * Retrieve and lock a entity by its unique ID.
  3. *
  4. * If the entity is found, a entity is returned. Otherwise a
  5. * {@link DocumentDoesNotExistException}.
  6. *
  7. * This method works similar to {@link #get(Class, Object)}, but in addition it (write) locks the
  8. * entity for the given lock time interval. Note that this lock time is hard capped to 30
  9. * seconds, even if provided with a higher value and is not configurable. The entity will unlock
  10. * afterwards automatically.
  11. *
  12. * Detecting an already locked entity is done by checking for
  13. * {@link TemporaryLockFailureException}. Note that this exception can also be raised in other
  14. * conditions, always when the error is transient and retrying may help.
  15. *
  16. * @param entityClass Entity class.
  17. * @param id id the unique ID of the entity.
  18. * @param lockTime the time to write lock the entity (max. 30 seconds).
  19. * @param <T> Entity type.
  20. * @return an {@link Observable} eventually containing the found {@link JsonDocument}.
  21. */
  22. default <T> T getAndLock(final Class<T> entityClass, final Object id, final int lockTime)
  23. throws DocumentDoesNotExistException {
  24. return async().getAndLock(entityClass, id, lockTime)
  25. .switchIfEmpty(notFound(entityClass, id))
  26. .toBlocking().single();
  27. }

代码示例来源:origin: ReactiveX/RxNetty

  1. @Override
  2. public void call(Subscriber<? super PooledConnection<R, W>> subscriber) {
  3. final long startTimeNanos = Clock.newStartTimeNanos();
  4. if (limitDeterminationStrategy.acquireCreationPermit(startTimeNanos, NANOSECONDS)) {
  5. Observable<Connection<R, W>> newConnObsv = hostConnector.getConnectionProvider()
  6. .newConnectionRequest();
  7. newConnObsv.map(new Func1<Connection<R, W>, PooledConnection<R, W>>() {
  8. @Override
  9. public PooledConnection<R, W> call(Connection<R, W> connection) {
  10. return PooledConnection.create(PooledConnectionProviderImpl.this,
  11. maxIdleTimeMillis, connection);
  12. }
  13. }).doOnError(new Action1<Throwable>() {
  14. @Override
  15. public void call(Throwable throwable) {
  16. limitDeterminationStrategy.releasePermit(); /*Before connect we acquired.*/
  17. }
  18. }).unsafeSubscribe(subscriber);
  19. } else {
  20. idleConnectionsHolder.poll()
  21. .switchIfEmpty(Observable.<PooledConnection<R, W>>error(
  22. new PoolExhaustedException("Client connection pool exhausted.")))
  23. .unsafeSubscribe(subscriber);
  24. }
  25. }
  26. });

代码示例来源:origin: ribot/ribot-app-android

  1. private Observable<List<Venue>> getVenuesRecoveryObservable(Throwable error) {
  2. return mPreferencesHelper.getVenuesAsObservable()
  3. .switchIfEmpty(Observable.<List<Venue>>error(error));
  4. }

代码示例来源:origin: ribot/ribot-app-android

  1. public Observable<Encounter> performBeaconEncounter(String uuid, int major, int minor) {
  2. Observable<RegisteredBeacon> errorObservable = Observable.error(
  3. new BeaconNotRegisteredException(uuid, major, minor));
  4. return mDatabaseHelper.findRegisteredBeacon(uuid, major, minor)
  5. .switchIfEmpty(errorObservable)
  6. .concatMap(new Func1<RegisteredBeacon, Observable<Encounter>>() {
  7. @Override
  8. public Observable<Encounter> call(RegisteredBeacon registeredBeacon) {
  9. return performBeaconEncounter(registeredBeacon.id);
  10. }
  11. });
  12. }

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

  1. @Override
  2. public void run() {
  3. Observable.<Integer>empty().switchIfEmpty(Observable.just(4, 5))
  4. .subscribe(new Action1<Integer>() {
  5. @Override
  6. public void call(Integer integer) {
  7. log(integer);
  8. }
  9. });
  10. }
  11. }

代码示例来源:origin: hawkular/hawkular-metrics

  1. @Override
  2. public Observable<Set<T>> call(Observable<T> metricIndexObservable) {
  3. return metricIndexObservable
  4. .toList()
  5. .switchIfEmpty(Observable.from(new HashSet<>()))
  6. .map((Func1<List<T>, HashSet<T>>) HashSet<T>::new);
  7. }
  8. }

代码示例来源:origin: org.hawkular.metrics/hawkular-metrics-core-service

  1. @Override
  2. public Observable<Set<T>> call(Observable<T> metricIndexObservable) {
  3. return metricIndexObservable
  4. .toList()
  5. .switchIfEmpty(Observable.from(new HashSet<>()))
  6. .map((Func1<List<T>, HashSet<T>>) HashSet<T>::new);
  7. }
  8. }

代码示例来源:origin: org.hawkular.metrics/hawkular-metrics-core-service

  1. @Override
  2. public Observable<Tenant> getTenants() {
  3. return dataAccess.findAllTenantIds()
  4. .map(row -> row.getString(0))
  5. .distinct()
  6. .flatMap(id ->
  7. dataAccess.findTenant(id)
  8. .map(Functions::getTenant)
  9. .switchIfEmpty(Observable.just(new Tenant(id)))
  10. );
  11. }

代码示例来源:origin: hawkular/hawkular-metrics

  1. @Override
  2. public Observable<Tenant> getTenants() {
  3. return dataAccess.findAllTenantIds()
  4. .map(row -> row.getString(0))
  5. .distinct()
  6. .flatMap(id ->
  7. dataAccess.findTenant(id)
  8. .map(Functions::getTenant)
  9. .switchIfEmpty(Observable.just(new Tenant(id)))
  10. );
  11. }

代码示例来源:origin: hawkular/hawkular-metrics

  1. @Override
  2. public Observable<Metric<T>> call(Observable<Metric<T>> metricObservable) {
  3. return metricObservable.flatMap(metric -> {
  4. long now = System.currentTimeMillis();
  5. MetricId<T> metricId = metric.getMetricId();
  6. return metricsService.findDataPoints(metricId, 0, now, 1, Order.ASC)
  7. .zipWith(metricsService.findDataPoints(metricId, 0, now, 1, Order.DESC), (p1, p2)
  8. -> new Metric<>(metric, p1.getTimestamp(), p2.getTimestamp()))
  9. .switchIfEmpty(Observable.just(metric));
  10. });
  11. }
  12. }

代码示例来源:origin: spring-projects/spring-data-couchbase

  1. @Override
  2. public <T>Observable<T> findBySpatialView(SpatialViewQuery query, Class<T> entityClass) {
  3. return querySpatialView(query)
  4. .flatMap(spatialViewResult -> spatialViewResult.error()
  5. .flatMap(error -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute spatial view query due to error:" + error.toString())))
  6. .switchIfEmpty(spatialViewResult.rows()))
  7. .map(row -> {
  8. AsyncSpatialViewRow asyncSpatialViewRow = (AsyncSpatialViewRow) row;
  9. return asyncSpatialViewRow.document(RawJsonDocument.class)
  10. .map(doc -> mapToEntity(doc.id(), doc, entityClass))
  11. .toBlocking().single();
  12. })
  13. .doOnError(throwable -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute spatial view query", throwable)));
  14. }

代码示例来源:origin: org.hawkular.metrics/hawkular-metrics-core-service

  1. @Override
  2. public Observable<Metric<T>> call(Observable<Metric<T>> metricObservable) {
  3. return metricObservable.flatMap(metric -> {
  4. long now = System.currentTimeMillis();
  5. MetricId<T> metricId = metric.getMetricId();
  6. return metricsService.findDataPoints(metricId, 0, now, 1, Order.ASC)
  7. .zipWith(metricsService.findDataPoints(metricId, 0, now, 1, Order.DESC), (p1, p2)
  8. -> new Metric<>(metric, p1.getTimestamp(), p2.getTimestamp()))
  9. .switchIfEmpty(Observable.just(metric));
  10. });
  11. }
  12. }

代码示例来源:origin: spring-projects/spring-data-couchbase

  1. @Override
  2. public <T>Observable<T> findByN1QLProjection(N1qlQuery query, Class<T> entityClass) {
  3. return queryN1QL(query)
  4. .flatMap(asyncN1qlQueryResult -> asyncN1qlQueryResult.errors()
  5. .flatMap(error -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query due to error:" + error.toString())))
  6. .switchIfEmpty(asyncN1qlQueryResult.rows()))
  7. .map(row -> {
  8. JsonObject json = ((AsyncN1qlQueryRow)row).value();
  9. T decoded = translationService.decodeFragment(json.toString(), entityClass);
  10. return decoded;
  11. })
  12. .doOnError(throwable -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query", throwable)));
  13. }

代码示例来源:origin: hawkular/hawkular-metrics

  1. public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) {
  2. // First check if the job exists
  3. return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId))
  4. .flatMap(jobRow -> session.execute(updateStatus.bind((byte) 1, timeSlice, jobId))
  5. .doOnError(t -> logger
  6. .warnf("There was an error updating the status to finished for %s in time " +
  7. "slice [%s]", jobId, timeSlice.getTime()))
  8. )
  9. .switchIfEmpty(Observable.<ResultSet>empty().doOnCompleted(() -> logger.warnf(
  10. "Attempt to update the status of a non-exist job [%s] " +
  11. "in time slice [%s]", jobId, timeSlice.getTime())));
  12. }

代码示例来源:origin: hawkular/hawkular-metrics

  1. public <T> Observable.Transformer<MetricId<T>, Metric<T>> enrichToMetric() {
  2. return t -> t
  3. .flatMap(id -> dataAccess.findMetricInMetricsIndex(id)
  4. .compose(new MetricsIndexRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL))
  5. .switchIfEmpty(dataAccess.findMetricInData(id) // This only verifies it exists..
  6. .compose(new MetricFromDataRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL))));
  7. }

代码示例来源:origin: org.hawkular.metrics/hawkular-metrics-core-service

  1. public <T> Observable.Transformer<MetricId<T>, Metric<T>> enrichToMetric() {
  2. return t -> t
  3. .flatMap(id -> dataAccess.findMetricInMetricsIndex(id)
  4. .compose(new MetricsIndexRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL))
  5. .switchIfEmpty(dataAccess.findMetricInData(id) // This only verifies it exists..
  6. .compose(new MetricFromDataRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL))));
  7. }

相关文章

Observable类方法