Java Code Examples for io.reactivex.Scheduler

The following examples show how to use io.reactivex.Scheduler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: YiZhi   Source File: RxBus.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 用于处理订阅事件在那个线程中执行
 *
 * @param observable       d
 * @param subscriberMethod d
 * @return Observable
 */
private Flowable postToObservable(Flowable observable, SubscriberMethod subscriberMethod) {
    Scheduler scheduler;
    switch (subscriberMethod.threadMode) {
        case MAIN:
            scheduler = AndroidSchedulers.mainThread();
            break;

        case NEW_THREAD:
            scheduler = Schedulers.newThread();
            break;

        case CURRENT_THREAD:
            scheduler = Schedulers.trampoline();
            break;
        default:
            throw new IllegalStateException("Unknown thread mode: " + subscriberMethod.threadMode);
    }
    return observable.observeOn(scheduler);
}
 
Example 2
Source Project: RxAndroidBle   Source File: DisconnectOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
DisconnectOperation(
        RxBleGattCallback rxBleGattCallback,
        BluetoothGattProvider bluetoothGattProvider,
        @Named(DeviceModule.MAC_ADDRESS) String macAddress,
        BluetoothManager bluetoothManager,
        @Named(ClientComponent.NamedSchedulers.BLUETOOTH_INTERACTION) Scheduler bluetoothInteractionScheduler,
        @Named(DeviceModule.DISCONNECT_TIMEOUT) TimeoutConfiguration timeoutConfiguration,
        ConnectionStateChangeListener connectionStateChangeListener) {
    this.rxBleGattCallback = rxBleGattCallback;
    this.bluetoothGattProvider = bluetoothGattProvider;
    this.macAddress = macAddress;
    this.bluetoothManager = bluetoothManager;
    this.bluetoothInteractionScheduler = bluetoothInteractionScheduler;
    this.timeoutConfiguration = timeoutConfiguration;
    this.connectionStateChangeListener = connectionStateChangeListener;
}
 
Example 3
Source Project: Reactive-Android-Programming   Source File: Sandbox.java    License: MIT License 6 votes vote down vote up
private static void demo2() throws Exception {
    final ExecutorService executor = Executors.newFixedThreadPool(1000);
    final Scheduler pooledScheduler = Schedulers.from(executor);

    Observable.range(1, 10000)
            .flatMap(i -> Observable.just(i)
                    .subscribeOn(pooledScheduler)
                    .map(Sandbox::importantLongTask)
            )
            .doOnTerminate(WAIT_LATCH::countDown)
            .map(Object::toString)
            .subscribe(e -> log("subscribe", e));

    WAIT_LATCH.await();
    executor.shutdown();
}
 
Example 4
CharacteristicLongWriteOperation(
        BluetoothGatt bluetoothGatt,
        RxBleGattCallback rxBleGattCallback,
        @Named(ClientComponent.NamedSchedulers.BLUETOOTH_INTERACTION) Scheduler bluetoothInteractionScheduler,
        @Named(ConnectionModule.OPERATION_TIMEOUT) TimeoutConfiguration timeoutConfiguration,
        BluetoothGattCharacteristic bluetoothGattCharacteristic,
        PayloadSizeLimitProvider batchSizeProvider,
        WriteOperationAckStrategy writeOperationAckStrategy,
        WriteOperationRetryStrategy writeOperationRetryStrategy,
        byte[] bytesToWrite) {
    this.bluetoothGatt = bluetoothGatt;
    this.rxBleGattCallback = rxBleGattCallback;
    this.bluetoothInteractionScheduler = bluetoothInteractionScheduler;
    this.timeoutConfiguration = timeoutConfiguration;
    this.bluetoothGattCharacteristic = bluetoothGattCharacteristic;
    this.batchSizeProvider = batchSizeProvider;
    this.writeOperationAckStrategy = writeOperationAckStrategy;
    this.writeOperationRetryStrategy = writeOperationRetryStrategy;
    this.bytesToWrite = bytesToWrite;
}
 
Example 5
Source Project: MyBookshelf   Source File: DownloadTaskImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void whenError(Scheduler scheduler) {
    if (!isDownloading) {
        return;
    }

    if (isFinishing()) {
        stopDownload();
        if (downloadBook.getSuccessCount() == 0) {
            onDownloadError(downloadBook);
        } else {
            onDownloadComplete(downloadBook);
        }
    } else {
        toDownload(scheduler);
    }
}
 
Example 6
Source Project: retrocache   Source File: RxJava2CachedCallAdapter.java    License: Apache License 2.0 6 votes vote down vote up
RxJava2CachedCallAdapter(Cache<String, byte[]> cachingSystem, Type responseType, Scheduler scheduler, Retrofit retrofit, Annotation[] annotations,
                         boolean mAsync, boolean mResult, boolean mBody, boolean mFlowable, boolean mSingle, boolean mMaybe,
                         boolean mCompletable) {

    this.mCachingSystem = cachingSystem;
    this.mResponseType = responseType;
    this.mScheduler = scheduler;
    this.mRetrofit = retrofit;
    this.mAnnotations = annotations;
    this.mAsync = mAsync;
    this.mResult = mResult;
    this.mBody = mBody;
    this.mFlowable = mFlowable;
    this.mSingle = mSingle;
    this.mMaybe = mMaybe;
    this.mCompletable = mCompletable;
}
 
Example 7
Source Project: RIBs   Source File: AndroidSchedulersRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void starting(Description description) {
  if (restoreHandlers) {
    // https://github.com/ReactiveX/RxAndroid/pull/358
    //            originalInitMainThreadInitHandler =
    // RxAndroidPlugins.getInitMainThreadScheduler();
    //            originalMainThreadHandler = RxAndroidPlugins.getMainThreadScheduler();
  }
  RxAndroidPlugins.reset();
  RxAndroidPlugins.setInitMainThreadSchedulerHandler(
      new Function<Callable<Scheduler>, Scheduler>() {
        @Override
        public Scheduler apply(Callable<Scheduler> schedulerCallable) throws Exception {
          return delegatingMainThreadScheduler;
        }
      });
  RxAndroidPlugins.setMainThreadSchedulerHandler(
      new Function<Scheduler, Scheduler>() {
        @Override
        public Scheduler apply(Scheduler scheduler) throws Exception {
          return delegatingMainThreadScheduler;
        }
      });
}
 
Example 8
Source Project: RxBus2   Source File: RxBus.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 用于处理订阅事件在那个线程中执行
 *
 * @param observable       d
 * @param subscriberMethod d
 * @return Observable
 */
private Flowable postToObservable(Flowable observable, SubscriberMethod subscriberMethod) {
    Scheduler scheduler;
    switch (subscriberMethod.threadMode) {
        case MAIN:
            scheduler = AndroidSchedulers.mainThread();
            break;

        case NEW_THREAD:
            scheduler = Schedulers.newThread();
            break;

        case CURRENT_THREAD:
            scheduler = Schedulers.trampoline();
            break;
        default:
            throw new IllegalStateException("Unknown thread mode: " + subscriberMethod.threadMode);
    }
    return observable.observeOn(scheduler);
}
 
Example 9
Source Project: storio   Source File: RxJavaUtils.java    License: Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static <T> Flowable<T> subscribeOn(
        @NonNull StorIOContentResolver storIOContentResolver,
        @NonNull Flowable<T> flowable
) {
    final Scheduler scheduler = storIOContentResolver.defaultRxScheduler();
    return scheduler != null ? flowable.subscribeOn(scheduler) : flowable;
}
 
Example 10
Source Project: AndroidGodEye   Source File: ThreadHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void setupRxjava() {
    TestScheduler testScheduler = new TestScheduler();
    RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() {
        @Override
        public Scheduler apply(Scheduler scheduler) throws Exception {
            return testScheduler;
        }
    });
}
 
Example 11
@Test
void custom_Scheduler_test() {
    Scheduler customScheduler = custom_Scheduler();
    Observable.just("Apple", "Orange", "Appla")
              .subscribeOn(customScheduler)
              .map(ConcurrencyTest::delayCalculation)
              .observeOn(customScheduler)
              .map(String::length)
              .subscribe(ConcurrencyTest::log);
    sleep(10000);
}
 
Example 12
Source Project: iroha-android   Source File: SendAssetInteractor.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
SendAssetInteractor(@Named(ApplicationModule.JOB) Scheduler jobScheduler,
                    @Named(ApplicationModule.UI) Scheduler uiScheduler,
                    ManagedChannel managedChannel, PreferencesUtil preferencesUtil) {
    super(jobScheduler, uiScheduler);
    this.channel = managedChannel;
    this.preferenceUtils = preferencesUtil;
}
 
Example 13
Source Project: rxjava2-jdbc   Source File: DatabaseCreator.java    License: Apache License 2.0 5 votes vote down vote up
public static Database create(int maxSize, boolean big, Scheduler scheduler) {
    NonBlockingConnectionPool pool = Pools.nonBlocking() //
            .connectionProvider(connectionProvider(nextUrl(), big)) //
            .maxPoolSize(maxSize) //
            .scheduler(scheduler) //
            .build();
    return Database.from(pool, () -> {
        pool.close();
        scheduler.shutdown();
    });
}
 
Example 14
@Inject
GetAccountTransactionsInteractor(@Named(ApplicationModule.JOB) Scheduler jobScheduler,
                                 @Named(ApplicationModule.UI) Scheduler uiScheduler,
                                 PreferencesUtil preferenceUtils, ManagedChannel channel) {
    super(jobScheduler, uiScheduler);
    this.preferenceUtils = preferenceUtils;
    this.channel = channel;
}
 
Example 15
Source Project: java-unified-sdk   Source File: AVObjectAsyncTest.java    License: Apache License 2.0 5 votes vote down vote up
public AVObjectAsyncTest(String testName) {
  super(testName);
  AppConfiguration.config(true, new AppConfiguration.SchedulerCreator() {
    public Scheduler create() {
      return Schedulers.newThread();
    }
  });
  Configure.initializeRuntime();
}
 
Example 16
Source Project: sqlbrite   Source File: BriteContentResolver.java    License: Apache License 2.0 5 votes vote down vote up
BriteContentResolver(ContentResolver contentResolver, Logger logger, Scheduler scheduler,
    ObservableTransformer<Query, Query> queryTransformer) {
  this.contentResolver = contentResolver;
  this.logger = logger;
  this.scheduler = scheduler;
  this.queryTransformer = queryTransformer;
}
 
Example 17
@NonNull
@Override
public Observable<Void> asObservable(BluetoothGatt bluetoothGatt,
                                     RxBleGattCallback rxBleGattCallback,
                                     Scheduler scheduler) throws Throwable {

    return Observable.fromCallable(() -> refreshDeviceCache(bluetoothGatt))
            .delay(delay_ms, TimeUnit.MILLISECONDS, Schedulers.computation())
            .subscribeOn(scheduler);
}
 
Example 18
public AdamantApiWrapper(AdamantApiBuilder apiBuilder, AdamantKeyGenerator keyGenerator, Scheduler scheduler) {
    this.apiBuilder = apiBuilder;
    this.keyGenerator = keyGenerator;
    this.scheduler = scheduler;

    buildApi();
}
 
Example 19
Source Project: java-unified-sdk   Source File: SetOperationTests.java    License: Apache License 2.0 5 votes vote down vote up
public SetOperationTests(String testName) {
  super(testName);
  AppConfiguration.config(true, new AppConfiguration.SchedulerCreator() {
    public Scheduler create() {
      return Schedulers.newThread();
    }
  });
  Configure.initializeRuntime();
}
 
Example 20
@Incoming("hello")
@Outgoing("out")
public Flowable<String> consume(Flowable<String> values) {
    Scheduler scheduler = Schedulers.from(executor);
    return values
            .observeOn(scheduler)
            .delay(1, TimeUnit.MILLISECONDS, scheduler)
            .doOnError(err -> {
                downstreamFailure = err;
            });
}
 
Example 21
Source Project: sqlbrite   Source File: BriteDatabase.java    License: Apache License 2.0 5 votes vote down vote up
BriteDatabase(SupportSQLiteOpenHelper helper, Logger logger, Scheduler scheduler,
    ObservableTransformer<Query, Query> queryTransformer) {
  this.helper = helper;
  this.logger = logger;
  this.scheduler = scheduler;
  this.queryTransformer = queryTransformer;
}
 
Example 22
Source Project: storio   Source File: RxJavaUtils.java    License: Apache License 2.0 5 votes vote down vote up
@CheckResult
@NonNull
public static Completable subscribeOn(
        @NonNull StorIOSQLite storIOSQLite,
        @NonNull Completable completable
) {
    final Scheduler scheduler = storIOSQLite.defaultRxScheduler();
    return scheduler != null ? completable.subscribeOn(scheduler) : completable;
}
 
Example 23
Source Project: atlas   Source File: RxAndroidPlugins.java    License: Apache License 2.0 5 votes vote down vote up
static Scheduler applyRequireNonNull(Function<Callable<Scheduler>, Scheduler> f, Callable<Scheduler> s) {
    Scheduler scheduler = apply(f,s);
    if (scheduler == null) {
        throw new NullPointerException("Scheduler Callable returned null");
    }
    return scheduler;
}
 
Example 24
Source Project: rxjava2-extras   Source File: Transformers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Buffers the source {@link Flowable} into {@link List}s, emitting Lists when
 * the size of a list reaches {@code maxSize} or if the elapsed time since last
 * emission from the source reaches the given duration.
 * 
 * @param maxSize
 *            max size of emitted lists
 * @param duration
 *            function that based on the last emission calculates the elapsed
 *            time to be used before emitting a buffered list
 * @param unit
 *            unit of {@code duration}
 * @param scheduler
 *            scheduler to use to schedule emission of a buffer (as a list) if
 *            the time since last emission from the source reaches duration
 * @param <T>
 *            type of the source stream items
 * @return source with operator applied
 */
public static <T> FlowableTransformer<T, List<T>> buffer(final int maxSize,
        final Function<? super T, ? extends Long> duration, final TimeUnit unit, final Scheduler scheduler) {

    final BiPredicate<List<T>, MyOptional<T>> condition = new BiPredicate<List<T>, MyOptional<T>>() {
        @Override
        public boolean test(List<T> list, MyOptional<T> x) throws Exception {
            return list.size() < maxSize && x.isPresent();
        }
    };
    Function<MyOptional<T>, Long> timeout = new Function<MyOptional<T>, Long>() {
        @Override
        public Long apply(MyOptional<T> t) throws Exception {
            return duration.apply(t.get());
        }
    };
    final FlowableTransformer<MyOptional<T>, MyOptional<T>> insert = insert(timeout, unit,
            Functions.constant(MyOptional.<T>empty()), scheduler);

    final FlowableTransformer<MyOptional<T>, List<T>> collectWhile = collectWhile( //
            // factory
            ListFactoryHolder.<T>factory(), //
            // add function
            MyOptional.<T>addIfPresent(), //
            // condition
            condition);

    return new FlowableTransformer<T, List<T>>() {
        @Override
        public Publisher<List<T>> apply(Flowable<T> source) {

            return source //
                    .map(MyOptional.<T>of()) //
                    .compose(insert) //
                    .compose(collectWhile)
                    // need this filter because sometimes nothing gets added to list
                    .filter(MyOptional.<T>listHasElements()); //
        }
    };
}
 
Example 25
Source Project: java-unified-sdk   Source File: StorageClient.java    License: Apache License 2.0 5 votes vote down vote up
private Observable wrapObservableInBackground(Observable observable) {
  if (null == observable) {
    return null;
  }
  Scheduler scheduler = Schedulers.io();
  if (asynchronized) {
    observable = observable.subscribeOn(scheduler);
  }
  if (null != defaultCreator) {
    observable = observable.observeOn(scheduler);
  }
  return observable;
}
 
Example 26
@Test public void runningWorkReportsBusy() {
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new Runnable() {
    @Override public void run() {
      assertBusy();
    }
  });
  delegate.triggerActions();
}
 
Example 27
Source Project: buffer-slayer   Source File: RxReporter.java    License: Apache License 2.0 5 votes vote down vote up
private MessageGroupSubscriber(long messageTimeoutNanos,
                               int bufferedMaxMessages,
                               Sender<M, R> sender,
                               Scheduler scheduler) {
  this.messageTimeoutNanos = messageTimeoutNanos == 0 ? Long.MAX_VALUE : messageTimeoutNanos;
  this.bufferedMaxMessages = bufferedMaxMessages;
  this.sender = sender;
  this.scheduler = scheduler;
}
 
Example 28
Source Project: xDrip   Source File: Ob1G5CollectionService.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
@Override
public Observable<Void> asObservable(BluetoothGatt bluetoothGatt,
                                     RxBleGattCallback rxBleGattCallback,
                                     Scheduler scheduler) throws Throwable {

    return Observable.fromCallable(() -> refreshDeviceCache(bluetoothGatt))
            .delay(delay_ms, TimeUnit.MILLISECONDS, Schedulers.computation())
            .subscribeOn(scheduler);
}
 
Example 29
Source Project: rxjava2-lab   Source File: Code5.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        Scheduler scheduler = Schedulers.from(newFixedThreadPool(10, threadFactory));

        CountDownLatch latch = new CountDownLatch(1);

        // Synchronous emission
        Observable<Object> observable = Observable.create(emitter -> {
            for (String superHero : SUPER_HEROES) {
                log("Emitting: " + superHero);
                emitter.onNext(superHero);
            }
            log("Completing");
            emitter.onComplete();
        });

        log("---------------- Subscribing");
        observable
            .subscribeOn(scheduler)
            .subscribe(
                item -> log("Received " + item),
                error -> log("Error"),
                () -> {
                    log("Complete");
                    latch.countDown();
                });
        log("---------------- Subscribed");

        latch.await();
    }
 
Example 30
Source Project: mockstar   Source File: BaseSchedulerProvider.java    License: MIT License 4 votes vote down vote up
@NonNull
Scheduler io();