@WorkerThread @Override public void parse(String itemId, String url) { Observable.defer(() -> fromCache(itemId)) .subscribeOn(Schedulers.immediate()) .switchIfEmpty(fromNetwork(itemId, url)) .map(content -> AndroidUtils.TextUtils.equals(EMPTY_CONTENT, content) ? null : content) .observeOn(Schedulers.immediate()) .subscribe(); }
/** * Get an entity/document by ID. The unique ID is constructed via * {@link N1Q#qualifyId(Class, Object)}. * * If the entity is found, a entity is returned. Otherwise a * {@link DocumentDoesNotExistException}. * * @param entityClass Entity class. * @param id Entity id. * @param mode Replica mode. * @param <T> Entity type. * @return An entity matching the id or an empty observable. */ default <T> T getFromReplica(final Class<T> entityClass, final Object id, final ReplicaMode mode) throws DocumentDoesNotExistException { return async().getFromReplica(entityClass, id, mode) .switchIfEmpty(notFound(entityClass, id)) .toBlocking().single(); }
/** * Get an entity/document by ID. The unique ID is constructed via * {@link N1Q#qualifyId(Class, Object)}. * * If the entity is found, a entity is returned. Otherwise a * {@link DocumentDoesNotExistException}. * * @param entityClass Entity class. * @param id Entity id. * @param <T> Entity type. * @return An entity matching the id or an empty observable. */ default <T> T get(final Class<T> entityClass, final Object id) throws DocumentDoesNotExistException { return async().get(entityClass, id) .switchIfEmpty(notFound(entityClass, id)) .toBlocking().single(); }
/** * Retrieve and touch an entity by its unique ID. * * If the entity is found, an entity is returned. Otherwise a * {@link DocumentDoesNotExistException}. * * This method works similar to {@link #get(Class, Object)}, but in addition it touches the * entity, which will reset its configured expiration time to the value provided. * * @param entityClass Entity class. * @param id id the unique ID of the entity. * @param expiry the new expiration time for the entity (in seconds). * @param <T> Entity type. * @return an {@link Observable} eventually containing the found {@link JsonDocument}. */ default <T> T getAndTouch(final Class<T> entityClass, final Object id, final int expiry) throws DocumentDoesNotExistException { return async().getAndTouch(entityClass, id, expiry) .switchIfEmpty(notFound(entityClass, id)) .toBlocking().single(); }
/** * Retrieve and lock a entity by its unique ID. * * If the entity is found, a entity is returned. Otherwise a * {@link DocumentDoesNotExistException}. * * This method works similar to {@link #get(Class, Object)}, but in addition it (write) locks the * entity for the given lock time interval. Note that this lock time is hard capped to 30 * seconds, even if provided with a higher value and is not configurable. The entity will unlock * afterwards automatically. * * Detecting an already locked entity is done by checking for * {@link TemporaryLockFailureException}. Note that this exception can also be raised in other * conditions, always when the error is transient and retrying may help. * * @param entityClass Entity class. * @param id id the unique ID of the entity. * @param lockTime the time to write lock the entity (max. 30 seconds). * @param <T> Entity type. * @return an {@link Observable} eventually containing the found {@link JsonDocument}. */ default <T> T getAndLock(final Class<T> entityClass, final Object id, final int lockTime) throws DocumentDoesNotExistException { return async().getAndLock(entityClass, id, lockTime) .switchIfEmpty(notFound(entityClass, id)) .toBlocking().single(); }
@Override public void call(Subscriber<? super PooledConnection<R, W>> subscriber) { final long startTimeNanos = Clock.newStartTimeNanos(); if (limitDeterminationStrategy.acquireCreationPermit(startTimeNanos, NANOSECONDS)) { Observable<Connection<R, W>> newConnObsv = hostConnector.getConnectionProvider() .newConnectionRequest(); newConnObsv.map(new Func1<Connection<R, W>, PooledConnection<R, W>>() { @Override public PooledConnection<R, W> call(Connection<R, W> connection) { return PooledConnection.create(PooledConnectionProviderImpl.this, maxIdleTimeMillis, connection); } }).doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { limitDeterminationStrategy.releasePermit(); /*Before connect we acquired.*/ } }).unsafeSubscribe(subscriber); } else { idleConnectionsHolder.poll() .switchIfEmpty(Observable.<PooledConnection<R, W>>error( new PoolExhaustedException("Client connection pool exhausted."))) .unsafeSubscribe(subscriber); } } });
private Observable<List<Venue>> getVenuesRecoveryObservable(Throwable error) { return mPreferencesHelper.getVenuesAsObservable() .switchIfEmpty(Observable.<List<Venue>>error(error)); }
public Observable<Encounter> performBeaconEncounter(String uuid, int major, int minor) { Observable<RegisteredBeacon> errorObservable = Observable.error( new BeaconNotRegisteredException(uuid, major, minor)); return mDatabaseHelper.findRegisteredBeacon(uuid, major, minor) .switchIfEmpty(errorObservable) .concatMap(new Func1<RegisteredBeacon, Observable<Encounter>>() { @Override public Observable<Encounter> call(RegisteredBeacon registeredBeacon) { return performBeaconEncounter(registeredBeacon.id); } }); }
@Override public void run() { Observable.<Integer>empty().switchIfEmpty(Observable.just(4, 5)) .subscribe(new Action1<Integer>() { @Override public void call(Integer integer) { log(integer); } }); } }
@Override public Observable<Set<T>> call(Observable<T> metricIndexObservable) { return metricIndexObservable .toList() .switchIfEmpty(Observable.from(new HashSet<>())) .map((Func1<List<T>, HashSet<T>>) HashSet<T>::new); } }
@Override public Observable<Set<T>> call(Observable<T> metricIndexObservable) { return metricIndexObservable .toList() .switchIfEmpty(Observable.from(new HashSet<>())) .map((Func1<List<T>, HashSet<T>>) HashSet<T>::new); } }
@Override public Observable<Tenant> getTenants() { return dataAccess.findAllTenantIds() .map(row -> row.getString(0)) .distinct() .flatMap(id -> dataAccess.findTenant(id) .map(Functions::getTenant) .switchIfEmpty(Observable.just(new Tenant(id))) ); }
@Override public Observable<Tenant> getTenants() { return dataAccess.findAllTenantIds() .map(row -> row.getString(0)) .distinct() .flatMap(id -> dataAccess.findTenant(id) .map(Functions::getTenant) .switchIfEmpty(Observable.just(new Tenant(id))) ); }
@Override public Observable<Metric<T>> call(Observable<Metric<T>> metricObservable) { return metricObservable.flatMap(metric -> { long now = System.currentTimeMillis(); MetricId<T> metricId = metric.getMetricId(); return metricsService.findDataPoints(metricId, 0, now, 1, Order.ASC) .zipWith(metricsService.findDataPoints(metricId, 0, now, 1, Order.DESC), (p1, p2) -> new Metric<>(metric, p1.getTimestamp(), p2.getTimestamp())) .switchIfEmpty(Observable.just(metric)); }); } }
@Override public <T>Observable<T> findBySpatialView(SpatialViewQuery query, Class<T> entityClass) { return querySpatialView(query) .flatMap(spatialViewResult -> spatialViewResult.error() .flatMap(error -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute spatial view query due to error:" + error.toString()))) .switchIfEmpty(spatialViewResult.rows())) .map(row -> { AsyncSpatialViewRow asyncSpatialViewRow = (AsyncSpatialViewRow) row; return asyncSpatialViewRow.document(RawJsonDocument.class) .map(doc -> mapToEntity(doc.id(), doc, entityClass)) .toBlocking().single(); }) .doOnError(throwable -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute spatial view query", throwable))); }
@Override public Observable<Metric<T>> call(Observable<Metric<T>> metricObservable) { return metricObservable.flatMap(metric -> { long now = System.currentTimeMillis(); MetricId<T> metricId = metric.getMetricId(); return metricsService.findDataPoints(metricId, 0, now, 1, Order.ASC) .zipWith(metricsService.findDataPoints(metricId, 0, now, 1, Order.DESC), (p1, p2) -> new Metric<>(metric, p1.getTimestamp(), p2.getTimestamp())) .switchIfEmpty(Observable.just(metric)); }); } }
@Override public <T>Observable<T> findByN1QLProjection(N1qlQuery query, Class<T> entityClass) { return queryN1QL(query) .flatMap(asyncN1qlQueryResult -> asyncN1qlQueryResult.errors() .flatMap(error -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query due to error:" + error.toString()))) .switchIfEmpty(asyncN1qlQueryResult.rows())) .map(row -> { JsonObject json = ((AsyncN1qlQueryRow)row).value(); T decoded = translationService.decodeFragment(json.toString(), entityClass); return decoded; }) .doOnError(throwable -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query", throwable))); }
public Observable<ResultSet> updateStatusToFinished(Date timeSlice, UUID jobId) { // First check if the job exists return session.executeAndFetch(findByIdAndSlice.bind(timeSlice, jobId)) .flatMap(jobRow -> session.execute(updateStatus.bind((byte) 1, timeSlice, jobId)) .doOnError(t -> logger .warnf("There was an error updating the status to finished for %s in time " + "slice [%s]", jobId, timeSlice.getTime())) ) .switchIfEmpty(Observable.<ResultSet>empty().doOnCompleted(() -> logger.warnf( "Attempt to update the status of a non-exist job [%s] " + "in time slice [%s]", jobId, timeSlice.getTime()))); }
public <T> Observable.Transformer<MetricId<T>, Metric<T>> enrichToMetric() { return t -> t .flatMap(id -> dataAccess.findMetricInMetricsIndex(id) .compose(new MetricsIndexRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL)) .switchIfEmpty(dataAccess.findMetricInData(id) // This only verifies it exists.. .compose(new MetricFromDataRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL)))); }
public <T> Observable.Transformer<MetricId<T>, Metric<T>> enrichToMetric() { return t -> t .flatMap(id -> dataAccess.findMetricInMetricsIndex(id) .compose(new MetricsIndexRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL)) .switchIfEmpty(dataAccess.findMetricInData(id) // This only verifies it exists.. .compose(new MetricFromDataRowTransformer<>(id.getTenantId(), id.getType(), defaultTTL)))); }