Refine search
return Observable.create((Observable.OnSubscribe<T>) subscriber -> { if (!subscriber.isUnsubscribed()) { try { final T response = getSyncInvoker().method(name, entity, responseType); if (!subscriber.isUnsubscribed()) { subscriber.onNext(response); if (!subscriber.isUnsubscribed()) { subscriber.onCompleted(); if (!subscriber.isUnsubscribed()) { subscriber.onError(throwable); }).subscribeOn(scheduler).observeOn(scheduler);
@Override public void call(Subscriber<? super Response<T>> subscriber) { // Since Call is a one-shot type, clone it for each new subscriber. Call<T> call = originalCall.clone(); final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber); subscriber.add(arbiter); subscriber.setProducer(arbiter); call.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { arbiter.emitResponse(response); } @Override public void onFailure(Call<T> call, Throwable t) { Exceptions.throwIfFatal(t); arbiter.emitError(t); } }); } }
@Override public void call(Subscriber<? super PooledConnection<R, W>> subscriber) { PooledConnection<R, W> idleConnection; while (!subscriber.isUnsubscribed() && (idleConnection = idleConnections.poll()) != null) { subscriber.onNext(idleConnection); } if (!subscriber.isUnsubscribed()) { subscriber.onCompleted(); } } });
@Override public void call(Subscriber<? super T> subscriber) { try { LazyList<T> lazyList = query.forCurrentThread().listLazyUncached(); try { for (T entity : lazyList) { if (subscriber.isUnsubscribed()) { break; } subscriber.onNext(entity); } } finally { lazyList.close(); } if (!subscriber.isUnsubscribed()) { subscriber.onCompleted(); } } catch (Throwable e) { Exceptions.throwIfFatal(e); subscriber.onError(e); } } });
public static Observable<Weather> getWeather(Context context, String cityId, WeatherDao weatherDao, boolean refreshNow) { Observable<Weather> observableForGetWeatherFromDB = Observable.create(subscriber -> { try { Weather weather = weatherDao.queryWeather(cityId); subscriber.onNext(weather); subscriber.onCompleted(); } catch (SQLException e) { throw Exceptions.propagate(e); case ApiConstants.WEATHER_DATA_SOURCE_TYPE_KNOW: observableForGetWeatherFromNetWork = ApiClient.weatherService.getKnowWeather(cityId) .map(knowWeather -> new KnowWeatherAdapter(knowWeather).getWeather()); break; case ApiConstants.WEATHER_DATA_SOURCE_TYPE_MI: observableForGetWeatherFromNetWork = ApiClient.weatherService.getMiWeather(cityId) .map(miWeather -> new MiWeatherAdapter(miWeather).getWeather()); break; case ApiConstants.WEATHER_DATA_SOURCE_TYPE_ENVIRONMENT_CLOUD: weatherDao.insertOrUpdateWeather(weather); } catch (SQLException e) { throw Exceptions.propagate(e);
@Override public Observable<UUID> setStatus( final UUID applicationId, final UUID jobId, final Status status, final Map<String, Object> data) { Preconditions.checkNotNull(applicationId, "app id is null"); Preconditions.checkNotNull(jobId, "job id is null"); Preconditions.checkNotNull(status, "status is null"); final Map<String,Object> dataMap = data != null ? data : new HashMap<String,Object>(); return Observable.create(sub -> { final String jobString = StringUtils.sanitizeUUID(jobId); final Id appId = CpNamingUtils.generateApplicationId(applicationId); final MapManager mapManager = mapManagerFactory.createMapManager(new MapScopeImpl(appId, "status")); try { final String dataString = MAPPER.writeValueAsString(dataMap); mapManager.putString(jobString + dataKey, dataString); mapManager.putString(jobString + statusKey, status.toString()); sub.onNext(jobId); sub.onCompleted(); } catch (Exception e) { logger.error("Failed to serialize map",e); throw new RuntimeException(e); } }); }
return observable.flatMap( idFilterResult -> { final Observable<FilterResult<Candidate>> candidates = Observable.create( subscriber -> { subscriber.onStart(); while ( !subscriber.isUnsubscribed() ) { if(subscriber.isUnsubscribed()){ return; result = createFilterResult( candidate, currentOffSet, idFilterResult.getPath() ); subscriber.onNext( result ); subscriber.onCompleted(); return; logger.error( "Unable to search candidates", t ); subscriber.onError( t );
private static <T> Observable<T> mockClient(T... ts) { return Observable.create((Subscriber<? super T> s) -> { // simulate latency try { Thread.sleep(1000); } catch (Exception e) { } for (T t : ts) { s.onNext(t); } s.onCompleted(); }).subscribeOn(Schedulers.io()); // note the use of subscribeOn to make an otherwise synchronous Observable async }
@Override public void call(Subscriber<? super Boolean> s) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } s.onNext(true); s.onCompleted(); }
/** * This is an artificial source to demonstrate an infinite stream that emits randomly */ public static Observable<Integer> hotStream() { return Observable.create((Subscriber<? super Integer> s) -> { int i = 0; while (!s.isUnsubscribed()) { s.onNext(i++); try { // sleep for a random amount of time // NOTE: Only using Thread.sleep here as an artificial demo. Thread.sleep((long) (Math.random() * 100)); } catch (Exception e) { // do nothing } } }).subscribeOn(Schedulers.newThread()); }
public static Observable<BaseDanmakuParser> downloadXML(final String uri) { return Observable.create((Observable.OnSubscribe<BaseDanmakuParser>) subscriber -> { if (TextUtils.isEmpty(uri)) { subscriber.onNext(new BaseDanmakuParser() { @Override protected IDanmakus parse() { return new Danmakus(); } }); } ILoader loader = null; try { HttpConnection.Response rsp = (HttpConnection.Response) Jsoup.connect(uri).timeout(20000).execute(); InputStream stream = new ByteArrayInputStream(BiliDanmukuCompressionTools. decompressXML(rsp.bodyAsBytes())); loader = DanmakuLoaderFactory. create(DanmakuLoaderFactory.TAG_BILI); loader.load(stream); } catch (IOException | DataFormatException | IllegalDataException e) { e.printStackTrace(); } BaseDanmakuParser parser = new BiliDanmukuParser(); assert loader != null; IDataSource<?> dataSource = loader.getDataSource(); parser.load(dataSource); subscriber.onNext(parser); }).subscribeOn(Schedulers.io()); } }
private void newConnectionReuseEvent(Channel channel, final ConnectionReuseEvent<R, W> event) { Subscriber<? super PooledConnection<R, W>> subscriber = event.getSubscriber(); if (isValidToEmit(subscriber)) { subscriber.onNext(event.getPooledConnection()); checkEagerSubscriptionIfConfigured(channel); } else { // If pooled connection not sent to the subscriber, release to the pool. event.getPooledConnection().close(false).subscribe(Actions.empty(), new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.error("Error closing connection.", throwable); } }); } }
@Override public void call( final Subscriber<? super T> outerOperation ) { CompositeSubscription csub = new CompositeSubscription(); //when a subscription is received, we need to subscribe on each observable SubscriberCoordinator coordinator = new SubscriberCoordinator( comparator, outerOperation, observables.length ); InnerObserver<T>[] innerObservers = new InnerObserver[observables.length]; //we have to do this in 2 steps to get the synchronization correct. We must set up our total inner observers //before starting subscriptions otherwise our assertions for completion or starting won't work properly for ( int i = 0; i < observables.length; i++ ) { //subscribe to each one and add it to the composite //create a new inner and subscribe final InnerObserver<T> inner = new InnerObserver<T>( coordinator, maxBufferSize, i ); coordinator.add( inner ); innerObservers[i] = inner; } /** * Once we're set up, begin the subscription to sub observables */ for ( int i = 0; i < observables.length; i++ ) { //subscribe after setting them up //add our subscription to the composite for future cancellation Subscription subscription = observables[i].subscribe( innerObservers[i] ); csub.add( subscription ); //add the internal composite subscription outerOperation.add( csub ); } }
return Observable.create((Subscriber<? super Integer> s) -> { final Iterator<Integer> iter = it.iterator(); final AtomicLong requested = new AtomicLong(); s.setProducer((long request) -> { if(s.isUnsubscribed()) { return; s.onNext(iter.next()); } else { s.onCompleted();
@Override public void call(Subscriber<? super Boolean> sub) { latch.countDown(); try { latch.await(); sub.onNext(true); sub.onCompleted(); } catch (InterruptedException e) { sub.onError(e); } } }).subscribeOn(Schedulers.computation()).toBlocking().toFuture());
@Override public void call(Subscriber<? super Connection<R, W>> subscriber) { if (isShutdown) { subscriber.onError(new IllegalStateException("Connection provider is shutdown.")); } idleConnectionsHolder.pollThisEventLoopConnections() .concatWith(connectIfAllowed()) .filter(new Func1<PooledConnection<R, W>, Boolean>() { @Override public Boolean call(PooledConnection<R, W> c) { boolean isUsable = c.isUsable(); if (!isUsable) { discardNow(c); } return isUsable; } }) .take(1) .lift(new ReuseSubscriberLinker()) .lift(new ConnectMetricsOperator()) .unsafeSubscribe(subscriber); } });
@Override public void onNext(Response<R> response) { if (response.isSuccessful()) { subscriber.onNext(response.body()); } else { subscriberTerminated = true; Throwable t = new HttpException(response); try { subscriber.onError(t); } catch (OnCompletedFailedException | OnErrorFailedException | OnErrorNotImplementedException e) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); CompositeException composite = new CompositeException(t, inner); RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); } } }
/** * Produces an observable that throws a {@link DocumentDoesNotExistException}. * * @param entityClass Entity class. * @param id Entity id. * @param <T> Entity type. * @return An observable that throws a {@link DocumentDoesNotExistException}. */ @SuppressWarnings("rawtypes") static <T> Observable<T> notFound(final Class entityClass, final Object id) { return Observable.create(s -> s.onError(new DocumentDoesNotExistException(N1Q.qualifyId(entityClass, id)))); }