io.reactivex.rxjava3.schedulers.Schedulers Java Examples

The following examples show how to use io.reactivex.rxjava3.schedulers.Schedulers. 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 File: TransformersTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void processingLongEffectsDoesNotBlockProcessingShorterEffects() {
  final List<String> effects = Arrays.asList("Hello", "Rx");

  PublishSubject<String> upstream = PublishSubject.create();
  Function<String, Integer> sleepyFunction =
      s -> {
        try {
          Thread.sleep(duration(s));
        } catch (InterruptedException ie) {
        }
        return s.length();
      };

  final List<Integer> results = new ArrayList<>();
  upstream
      .compose(Transformers.fromFunction(sleepyFunction, Schedulers.io()))
      .subscribe(results::add);

  Observable.fromIterable(effects).subscribe(upstream);

  await().atMost(durationForEffects(effects)).until(() -> results.equals(expected(effects)));
}
 
Example #2
Source File: SomeBlocking.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    Observable
    .range(1, 20)
    .flatMap(
            integer -> {
                if (integer % 5 != 0) {
                    return Observable
                            .just(integer);
                }

                return Observable
                        .just(-integer)
                        .observeOn(Schedulers.io());
            },
            false,
            1
    )
    .ignoreElements()
    .blockingAwait();
}
 
Example #3
Source File: PublishRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void addRemoveRance() throws Exception {

    for (int i = 0; i < 100; i++) {
        final PublishRelay<Integer> pp = PublishRelay.create();

        final TestObserver<Integer> ts = pp.test();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                pp.subscribe();
            }
        };
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.io());
    }
}
 
Example #4
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void addRemoveRace() {
    for (int i = 0; i < 500; i++) {
        final BehaviorRelay<Object> p = BehaviorRelay.create();

        final TestObserver<Object> ts = p.test();

        Runnable r1 = new Runnable() {
            @Override
            @SuppressWarnings("CheckReturnValue")
            public void run() {
                p.test();
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());
    }
}
 
Example #5
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeRace() {
    for (int i = 0; i < 500; i++) {
        final ReplayRelay<Integer> rp = ReplayRelay.create();

        Runnable r1 = new Runnable() {
            @Override
            @SuppressWarnings("CheckReturnValue")
            public void run() {
                rp.test();
            }
        };

        TestHelper.race(r1, r1, Schedulers.single());
    }
}
 
Example #6
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeCancelRace() {
    for (int i = 0; i < 500; i++) {
        final TestObserver<Integer> ts = new TestObserver<Integer>();

        final ReplayRelay<Integer> rp = ReplayRelay.create();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                rp.subscribe(ts);
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());
    }
}
 
Example #7
Source File: PublishRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void addRemoveRance() throws Exception {

    for (int i = 0; i < 100; i++) {
        final PublishRelay<Integer> pp = PublishRelay.create();

        final TestObserver<Integer> ts = pp.test();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                pp.subscribe();
            }
        };
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.io());
    }
}
 
Example #8
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void addRemoveRace() {
    for (int i = 0; i < 500; i++) {
        final BehaviorRelay<Object> p = BehaviorRelay.create();

        final TestObserver<Object> ts = p.test();

        Runnable r1 = new Runnable() {
            @Override
            @SuppressWarnings("CheckReturnValue")
            public void run() {
                p.test();
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());
    }
}
 
Example #9
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeRace() {
    for (int i = 0; i < 500; i++) {
        final ReplayRelay<Integer> rp = ReplayRelay.create();

        Runnable r1 = new Runnable() {
            @Override
            @SuppressWarnings("CheckReturnValue")
            public void run() {
                rp.test();
            }
        };

        TestHelper.race(r1, r1, Schedulers.single());
    }
}
 
Example #10
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeCancelRace() {
    for (int i = 0; i < 500; i++) {
        final TestObserver<Integer> ts = new TestObserver<Integer>();

        final ReplayRelay<Integer> rp = ReplayRelay.create();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                rp.subscribe(ts);
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());
    }
}
 
Example #11
Source File: LocalRepository.java    From GetApk with MIT License 6 votes vote down vote up
public Disposable getAndSort(Context context, final boolean sortByTime, final DateFormat dateFormat, KWSubscriber<ItemArray> subscriber) {
    return Flowable.just(new WeakReference<>(context))
            .flatMap(new Function<WeakReference<Context>, Publisher<List<App>>>() {
                @Override
                public Publisher<List<App>> apply(WeakReference<Context> weakContext) throws Exception {
                    List<App> apps = getApps();
                    if (apps == null) {
                        return getApps(weakContext.get(), dateFormat);
                    } else {
                        return Flowable.just(apps);
                    }
                }
            })
            .map(new SortFunction(dateFormat, sortByTime))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(subscriber);
}
 
Example #12
Source File: LocalRepository.java    From GetApk with MIT License 6 votes vote down vote up
@Deprecated
public Disposable saveApk(App app, final String dest, final KWSubscriber<String> subscriber) {
    return Flowable.just(app)
            .map(new Function<App, String>() {
                @Override
                public String apply(App source) throws Exception {
                    String fileName = source.name + "_" + source.versionName + ".apk";
                    return FileUtil.copy(source.apkPath, dest, fileName, new OnCopyListener() {
                        @Override
                        public void inProgress(final float progress) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    subscriber.inProgress(progress);
                                }
                            });
                        }
                    }).getAbsolutePath();
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(subscriber);
}
 
Example #13
Source File: Wallet.java    From zap-android with MIT License 6 votes vote down vote up
/**
 * This will fetch the current balance from LND.
 * All Listeners registered to BalanceListener will be informed about any changes.
 */
public void fetchBalanceFromLND() {

    Single<WalletBalanceResponse> walletBalance = LndConnection.getInstance().getLightningService().walletBalance(WalletBalanceRequest.newBuilder().build());
    Single<ChannelBalanceResponse> channelBalance = LndConnection.getInstance().getLightningService().channelBalance(ChannelBalanceRequest.newBuilder().build());
    Single<PendingChannelsResponse> pendingChannels = LndConnection.getInstance().getLightningService().pendingChannels(PendingChannelsRequest.newBuilder().build());

    compositeDisposable.add(Single.zip(walletBalance, channelBalance, pendingChannels, (walletBalanceResponse, channelBalanceResponse, pendingChannelsResponse) -> {

        setOnChainBalance(walletBalanceResponse.getTotalBalance(), walletBalanceResponse.getConfirmedBalance(), walletBalanceResponse.getUnconfirmedBalance());
        setChannelBalance(channelBalanceResponse.getBalance(), channelBalanceResponse.getPendingOpenBalance());
        setChannelBalanceLimbo(pendingChannelsResponse.getTotalLimboBalance());

        return true;
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(aBoolean -> {
        // Zip executed without error
        broadcastBalanceUpdate();
    }, throwable -> ZapLog.debug(LOG_TAG, "Exception in fetch balance task: " + throwable.getMessage())));
}
 
Example #14
Source File: LocalRepository.java    From GetApk with MIT License 6 votes vote down vote up
public Disposable saveApk(ContentResolver resolver, App app, final Uri dest, final KWSubscriber<Uri> subscriber) {
    return Flowable.just(app)
            .map(new Function<App, Uri>() {
                @Override
                public Uri apply(App source) throws Exception {
                    FileUtil.copy(resolver, Uri.fromFile(new File(source.apkPath)), dest, new OnCopyListener() {
                        @Override
                        public void inProgress(final float progress) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    subscriber.inProgress(progress);
                                }
                            });
                        }
                    });
                    return dest;
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(subscriber);
}
 
Example #15
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test
public void dispose() {
    TestHelper.checkDisposed(ReplayRelay.create());

    TestHelper.checkDisposed(ReplayRelay.createUnbounded());

    TestHelper.checkDisposed(ReplayRelay.createWithSize(10));

    TestHelper.checkDisposed(
        ReplayRelay.createWithTimeAndSize(1, TimeUnit.SECONDS, Schedulers.single(), 10));
}
 
Example #16
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void subscribeOnNextRace() {
    for (int i = 0; i < 500; i++) {
        final BehaviorRelay<Object> p = BehaviorRelay.createDefault((Object)1);

        final TestObserver[] ts = { null };

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                ts[0] = p.test();
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                p.accept(2);
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());

        if (ts[0].values().size() == 1) {
            ts[0].assertValue(2).assertNoErrors().assertNotComplete();
        } else {
            ts[0].assertValues(1, 2).assertNoErrors().assertNotComplete();
        }
    }
}
 
Example #17
Source File: SerializedRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test
public void onNextOnNextRace() {
    for (int i = 0; i < 500; i++) {
        final Relay<Integer> s = PublishRelay.<Integer>create().toSerialized();

        TestObserver<Integer> ts = s.test();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                s.accept(1);
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                s.accept(2);
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());

        List<Integer> actual = ts.assertNoErrors().assertNotComplete().values();
        List<Integer> expected = Arrays.asList(1, 2);
        assertTrue("The collections are not the same", actual.size() == expected.size()
                && actual.containsAll(expected) && expected.containsAll(actual));
    }
}
 
Example #18
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test
public void createWithTimeAndSizeInvalidCapacity() {
    try {
        ReplayRelay.createWithTimeAndSize(1, TimeUnit.DAYS, Schedulers.computation(), -99);
        fail("Didn't throw IllegalArgumentException");
    } catch (IllegalArgumentException ex) {
        assertEquals("maxSize > 0 required but it was -99", ex.getMessage());
    }
}
 
Example #19
Source File: AppDelegate.java    From GetApk with MIT License 5 votes vote down vote up
public void getIcon() {
    recycler();
    final WeakReference<App> appWeak = new WeakReference<>(mApp);
    mDisposable = Flowable.just(itemView.getContext().getApplicationContext().getPackageManager())
            .map(new Function<PackageManager, Drawable>() {
                @Override
                public Drawable apply(PackageManager pm) throws Exception {
                    App app = appWeak.get();
                    if (app != null){
                        return app.applicationInfo.loadIcon(pm);
                    }else {
                        throw new Exception("app is null");
                    }
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSubscriber<Drawable>() {
                @Override
                public void onNext(Drawable drawable) {
                    mIconImg.setImageDrawable(drawable);
                }

                @Override
                public void onError(Throwable t) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example #20
Source File: ReplayRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test
public void cancelRace() {
    for (int i = 0; i < 500; i++) {

        final ReplayRelay<Integer> rp = ReplayRelay.create();
        final TestObserver<Integer> ts1 = rp.test();
        final TestObserver<Integer> ts2 = rp.test();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                ts1.dispose();
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                ts2.dispose();
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());

        assertFalse(rp.hasObservers());
    }
}
 
Example #21
Source File: ReactiveBatchProcessorV2.java    From code-examples with MIT License 5 votes vote down vote up
public void start() {
  // WARNING: this code doesn't work as expected
  messageSource.getMessageBatches()
      .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
      .doOnNext(batch -> logger.log(batch.toString()))
      .flatMap(batch -> Flowable.fromIterable(batch.getMessages()))
      .flatMapSingle(m -> Single.defer(() -> Single.just(messageHandler.handleMessage(m)))
          .subscribeOn(threadPoolScheduler(threads, threadPoolQueueSize)))
      .subscribeWith(new SimpleSubscriber<>(threads, 1));
}
 
Example #22
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void subscribeOnNextRace() {
    for (int i = 0; i < 500; i++) {
        final BehaviorRelay<Object> p = BehaviorRelay.createDefault((Object)1);

        final TestObserver[] ts = { null };

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                ts[0] = p.test();
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                p.accept(2);
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());

        if (ts[0].values().size() == 1) {
            ts[0].assertValue(2).assertNoErrors().assertNotComplete();
        } else {
            ts[0].assertValues(1, 2).assertNoErrors().assertNotComplete();
        }
    }
}
 
Example #23
Source File: SerializedRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test
public void onNextOnNextRace() {
    for (int i = 0; i < 500; i++) {
        final Relay<Integer> s = PublishRelay.<Integer>create().toSerialized();

        TestObserver<Integer> ts = s.test();

        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                s.accept(1);
            }
        };

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                s.accept(2);
            }
        };

        TestHelper.race(r1, r2, Schedulers.single());

        List<Integer> actual = ts.assertNoErrors().assertNotComplete().values();
        List<Integer> expected = Arrays.asList(1, 2);
        assertTrue("The collections are not the same", actual.size() == expected.size()
                && actual.containsAll(expected) && expected.containsAll(actual));
    }
}
 
Example #24
Source File: RxJava3FlowableService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Produces("application/json")
@Path("textJsonImplicitListAsyncStream")
public void getJsonImplicitListStreamingAsync(@Suspended AsyncResponse ar) {
    Flowable.just("Hello", "Ciao")
        .map(HelloWorldBean::new)
        .subscribeOn(Schedulers.computation())
        .subscribe(new JsonStreamingAsyncSubscriber<HelloWorldBean>(ar));
}
 
Example #25
Source File: FlowableRxInvokerImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private <T> Flowable<T> create(Supplier<T> supplier) {
    Flowable<T> flowable = Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(FlowableEmitter<T> emitter) throws Exception {
            try {
                T response = supplier.get();
                if (!emitter.isCancelled()) {
                    emitter.onNext(response);
                }
                
                if (!emitter.isCancelled()) {
                    emitter.onComplete();
                }
            } catch (Throwable e) {
                if (!emitter.isCancelled()) {
                    emitter.onError(e);
                }
            }
        }
    }, BackpressureStrategy.DROP);
    
    if (sc == null) {
        return flowable.subscribeOn(Schedulers.io());
    }
    
    return flowable.subscribeOn(sc).observeOn(sc);
}
 
Example #26
Source File: ObservableRxInvokerImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private <T> Observable<T> create(Supplier<T> supplier) {
    Observable<T> observable = Observable.create(new ObservableOnSubscribe<T>() {
        @Override
        public void subscribe(ObservableEmitter<T> emitter) throws Exception {
            try {
                T response = supplier.get();
                if (!emitter.isDisposed()) {
                    emitter.onNext(response);
                }
                
                if (!emitter.isDisposed()) {
                    emitter.onComplete();
                }
            } catch (Throwable e) {
                if (!emitter.isDisposed()) {
                    emitter.onError(e);
                }
            }
        }
    });
    
    if (sc == null) {
        return observable.subscribeOn(Schedulers.io());
    }
    
    return observable.subscribeOn(sc).observeOn(sc);
}
 
Example #27
Source File: RxJavaLiveVideo.java    From tutorials with MIT License 5 votes vote down vote up
public static Disposable streamLiveVideo(long produceDelay, long consumeDelay, int bufferSize, Runnable onError) {
    return Flowable
      .fromStream(Stream.iterate(new VideoFrame(0), videoFrame -> {
          sleep(produceDelay);
          return new VideoFrame(videoFrame.getNumber() + 1);
      }))
      .subscribeOn(Schedulers.from(Executors.newSingleThreadScheduledExecutor()), true)
      .onBackpressureBuffer(bufferSize, null, BackpressureOverflowStrategy.ERROR)
      .observeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
      .subscribe(item -> {
          sleep(consumeDelay);
      }, throwable -> {
          onError.run();
      });
}
 
Example #28
Source File: ReactiveBatchProcessorV1.java    From code-examples with MIT License 5 votes vote down vote up
public void start() {
  // WARNING: this code doesn't work as expected
  messageSource.getMessageBatches()
      .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor()))
      .doOnNext(batch -> logger.log(batch.toString()))
      .flatMap(batch -> Flowable.fromIterable(batch.getMessages()))
      .flatMapSingle(m -> Single.just(messageHandler.handleMessage(m))
          .subscribeOn(threadPoolScheduler(threads, threadPoolQueueSize)))
      .subscribeWith(new SimpleSubscriber<>(threads, 1));
}
 
Example #29
Source File: PixelTraversalController.java    From Image-Cipher with Apache License 2.0 5 votes vote down vote up
void setClickObservable(Observable<Point> observable) {
  logger.info("Setting observable");
  disposable = observable.subscribeOn(Schedulers.computation())
      .subscribe(point -> {
        startingPoint = point;
        runPixelTraversal();
      });
}
 
Example #30
Source File: ReactiveBatchProcessorV2.java    From code-examples with MIT License 5 votes vote down vote up
private Scheduler threadPoolScheduler(int poolSize, int queueSize) {
  return Schedulers.from(new ThreadPoolExecutor(
      poolSize,
      poolSize,
      0L,
      TimeUnit.SECONDS,
      new LinkedBlockingDeque<>(queueSize)
  ));
}