io.reactivex.rxjava3.core.Flowable Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Flowable. 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: QueryObserverTest.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
@Test
public void flowableOneByOne() {
    publisher.setQueryResult(listResult);

    Flowable<String> flowable = RxQuery.flowableOneByOne(mockQuery.getQuery());

    TestObserver testObserver = new TestObserver();
    testObserver.resetLatch(2);
    //noinspection ResultOfMethodCallIgnored
    flowable.subscribe(testObserver);

    testObserver.assertLatchCountedDown(2);
    assertEquals(2, testObserver.receivedChanges.size());
    assertEquals(1, testObserver.receivedChanges.get(0).size());
    assertEquals(1, testObserver.receivedChanges.get(1).size());
    assertNull(testObserver.error);

    testObserver.receivedChanges.clear();

    publisher.publish();
    testObserver.assertNoMoreResults();
}
 
Example #2
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void errorClearsCacheAndResubscribes() {
  List<String> start = new ArrayList<>();
  start.add("initA");

  PublishProcessor<String> upstream = PublishProcessor.create();
  Flowable<String> replayed = upstream.startWithIterable(start).compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  replayed.subscribe(subscriber1);
  subscriber1.assertValues("initA");

  TestSubscriber<String> observer2 = new TestSubscriber<>();
  replayed.subscribe(observer2);
  subscriber1.assertValues("initA");

  RuntimeException r = new RuntimeException();
  upstream.onError(r);
  subscriber1.assertError(r);
  observer2.assertError(r);

  start.set(0, "initB");

  TestSubscriber<String> observer3 = new TestSubscriber<>();
  replayed.subscribe(observer3);
  observer3.assertValues("initB");
}
 
Example #3
Source File: CacheAndRemoteStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Publisher<Record<T>> execute(RxCache rxCache, String key, Flowable<T> source, Type type) {

    Flowable<Record<T>> cache = rxCache.<T>load2Flowable(key, type);

    Flowable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return Flowable.concatDelayError(Arrays.asList(cache, remote))
            .filter(new Predicate<Record<T>>() {
                @Override
                public boolean test(@NonNull Record<T> record) throws Exception {
                    return record.getData() != null;
                }
            });
}
 
Example #4
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void completeClearsCacheAndResubscribesStartingWithDefault() {
  List<String> start = new ArrayList<>();
  start.add("initA");

  PublishProcessor<String> upstream = PublishProcessor.create();
  Flowable<String> replayed =
      upstream.startWithIterable(start).compose(ReplayingShare.createWithDefault("default"));

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  replayed.subscribe(subscriber1);
  subscriber1.assertValues("default", "initA");

  TestSubscriber<String> observer2 = new TestSubscriber<>();
  replayed.subscribe(observer2);
  subscriber1.assertValues("default", "initA");

  upstream.onComplete();
  subscriber1.assertComplete();
  observer2.assertComplete();

  start.set(0, "initB");

  TestSubscriber<String> observer3 = new TestSubscriber<>();
  replayed.subscribe(observer3);
  observer3.assertValues("default", "initB");
}
 
Example #5
Source File: RemoteFirstStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Publisher<Record<T>> execute(RxCache rxCache, String key, Flowable<T> source, Type type) {

    Flowable<Record<T>> cache = rxCache.<T>load2Flowable(key, type);

    Flowable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return remote.switchIfEmpty(cache);
}
 
Example #6
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void completeClearsCacheAndResubscribes() {
  List<String> start = new ArrayList<>();
  start.add("initA");

  PublishProcessor<String> upstream = PublishProcessor.create();
  Flowable<String> replayed = upstream.startWithIterable(start).compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  replayed.subscribe(subscriber1);
  subscriber1.assertValues("initA");

  TestSubscriber<String> observer2 = new TestSubscriber<>();
  replayed.subscribe(observer2);
  subscriber1.assertValues("initA");

  upstream.onComplete();
  subscriber1.assertComplete();
  observer2.assertComplete();

  start.set(0, "initB");

  TestSubscriber<String> observer3 = new TestSubscriber<>();
  replayed.subscribe(observer3);
  observer3.assertValues("initB");
}
 
Example #7
Source File: LocalRepository.java    From GetApk with MIT License 6 votes vote down vote up
private Publisher<List<App>> getApps(Context context, final DateFormat dateFormat) {
    return Flowable.just(new WeakReference<>(context))
            .map(new Function<WeakReference<Context>, List<App>>() {
                @Override
                public List<App> apply(WeakReference<Context> weakContext) throws Exception {
                    final PackageManager pm = weakContext.get().getPackageManager();
                    List<PackageInfo> infos = pm.getInstalledPackages(0);
                    List<App> apps = new ArrayList<>();
                    for (PackageInfo info : infos) {
                        App app = new App(info, pm);
                        app.isFormFile = false;
                        Date date = new Date(info.lastUpdateTime);
                        app.time = dateFormat.format(date);
                        apps.add(app);
                    }
                    setApps(apps);
                    return apps;
                }
            });
}
 
Example #8
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void streamsDoNotShareInstances() {
  PublishProcessor<String> subjectA = PublishProcessor.create();
  Flowable<String> flowableA = subjectA.compose(ReplayingShare.<String>instance());
  TestSubscriber<String> subscriberA1 = new TestSubscriber<>();
  flowableA.subscribe(subscriberA1);

  PublishProcessor<String> subjectB = PublishProcessor.create();
  Flowable<String> flowableB = subjectB.compose(ReplayingShare.<String>instance());
  TestSubscriber<String> subscriberB1 = new TestSubscriber<>();
  flowableB.subscribe(subscriberB1);

  subjectA.onNext("Foo");
  subscriberA1.assertValues("Foo");
  subjectB.onNext("Bar");
  subscriberB1.assertValues("Bar");

  TestSubscriber<String> subscriberA2 = new TestSubscriber<>();
  flowableA.subscribe(subscriberA2);
  subscriberA2.assertValues("Foo");

  TestSubscriber<String> subscriberB2 = new TestSubscriber<>();
  flowableB.subscribe(subscriberB2);
  subscriberB2.assertValues("Bar");
}
 
Example #9
Source File: DataServiceTest.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataServiceWithBackPressureIncomplete() throws InterruptedException {
    DataService dataService = new DataServiceImpl(executor);
    Flowable<DataItem> dataFlow = dataService.getDataFlowWithBackPressure(new DataQuery("query2-back-pressure-incomplete", 10));
    LOG.info("query submitted");
    SynchronousDataSubscriber dataSubscriber = new SynchronousDataSubscriber();
    dataFlow.subscribe(dataSubscriber);

    dataSubscriber.request(5);
    dataSubscriber.await(2, TimeUnit.SECONDS);
    LOG.info("evaluating test results");

    Assert.assertTrue(dataSubscriber.getErrors().size() == 0);
    Assert.assertTrue(dataSubscriber.getResults().size() == 5);
    Assert.assertFalse(dataSubscriber.isCompleted());
    Assert.assertNotNull(dataSubscriber.getSubscription());
}
 
Example #10
Source File: DataServiceTest.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataServiceWithBackPressureComplete() throws InterruptedException {
    DataService dataService = new DataServiceImpl(executor);
    Flowable<DataItem> dataFlow = dataService.getDataFlowWithBackPressure(new DataQuery("query1-back-pressure-complete", 10));
    LOG.info("query submitted");
    SynchronousDataSubscriber dataSubscriber = new SynchronousDataSubscriber();
    dataFlow.subscribe(dataSubscriber);

    dataSubscriber.request(10);
    dataSubscriber.await(10, TimeUnit.SECONDS);
    LOG.info("evaluating test results");

    Assert.assertTrue(dataSubscriber.getErrors().size() == 0);
    Assert.assertTrue(dataSubscriber.getResults().size() == 10);
    Assert.assertTrue(dataSubscriber.isCompleted());
    Assert.assertNotNull(dataSubscriber.getSubscription());
}
 
Example #11
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void backpressureHonoredWhenCached() {
  PublishProcessor<String> subject = PublishProcessor.create();
  Flowable<String> flowable = subject.compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  flowable.subscribe(subscriber1);
  subscriber1.assertNoValues();

  subject.onNext("Foo");
  subscriber1.assertValues("Foo");

  TestSubscriber<String> subscriber2 = new TestSubscriber<>(0);
  flowable.subscribe(subscriber2);
  subscriber2.assertNoValues();

  subject.onNext("Bar"); // Replace the cached value...
  subscriber2.request(1); // ...and ensure new requests see it.
  subscriber2.assertValues("Bar");
}
 
Example #12
Source File: CacheFirstStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Publisher<Record<T>> execute(RxCache rxCache, String key, Flowable<T> source, Type type) {

    Flowable<Record<T>> cache = rxCache.<T>load2Flowable(key, type);

    Flowable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return cache.switchIfEmpty(remote);
}
 
Example #13
Source File: RemoteOnlyStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Publisher<Record<T>> execute(RxCache rxCache, String key, Flowable<T> source, Type type, BackpressureStrategy backpressureStrategy) {

    Flowable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return remote;
}
 
Example #14
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void valueMissedWhenNoSubscribers() {
  PublishProcessor<String> subject = PublishProcessor.create();
  Flowable<String> flowable = subject.compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  flowable.subscribe(subscriber1);
  subscriber1.assertNoValues();
  subscriber1.cancel();

  subject.onNext("Foo");
  subscriber1.assertNoValues();

  TestSubscriber<String> subscriber2 = new TestSubscriber<>();
  flowable.subscribe(subscriber2);
  subscriber2.assertNoValues();
}
 
Example #15
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 6 votes vote down vote up
@Test public void initialValueToNewSubscriberAfterUnsubscribe() {
  PublishProcessor<String> subject = PublishProcessor.create();
  Flowable<String> flowable = subject.compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  flowable.subscribe(subscriber1);
  subscriber1.assertNoValues();

  subject.onNext("Foo");
  subscriber1.assertValues("Foo");
  subscriber1.cancel();

  TestSubscriber<String> subscriber2 = new TestSubscriber<>();
  flowable.subscribe(subscriber2);
  subscriber2.assertValues("Foo");
}
 
Example #16
Source File: RemoteOnlyStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Publisher<Record<T>> execute(RxCache rxCache, String key, Flowable<T> source, Type type) {

    Flowable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return remote;
}
 
Example #17
Source File: TimeLimiterTransformerPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotTimeout() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ofMinutes(1)));
    TestSubscriber<Long> subscriber = Flowable.interval(1, TimeUnit.SECONDS)
        .take(2)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    subscriber.assertValueCount(2)
        .assertComplete();
    then(timeLimiter).should(times(3))
        .onSuccess();
}
 
Example #18
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 #19
Source File: FlowableCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInvokeReleasePermissionReleaseOnCancel() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);

    Flowable.just(1)
        .delay(1, TimeUnit.DAYS)
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test()
        .cancel();

    then(circuitBreaker).should().releasePermission();
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
    then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
 
Example #20
Source File: FlowableBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPropagateError() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Flowable.error(new IOException("BAM!"))
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertError(IOException.class)
        .assertNotComplete();

    then(bulkhead).should().onComplete();
}
 
Example #21
Source File: DefaultDispatchManager.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Flowable<T> asFlowable(final BackpressureStrategy backpressureStrategy) {
    return Flowable.create(emitter -> {
        internalHandler = emitter::onNext;
        emitter.setCancellable(this::close);
    }, backpressureStrategy);
}
 
Example #22
Source File: FlowableBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitAllEvents() {
    given(bulkhead.tryAcquirePermission()).willReturn(true);

    Flowable.fromArray("Event 1", "Event 2")
        .compose(BulkheadOperator.of(bulkhead))
        .test()
        .assertResult("Event 1", "Event 2");

    then(bulkhead).should().onComplete();
}
 
Example #23
Source File: FlowableCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInvokeOnSuccessOnCancelWhenOneEventWasEmitted() {
    given(circuitBreaker.tryAcquirePermission()).willReturn(true);

    Flowable.just(1, 2, 3)
        .compose(CircuitBreakerOperator.of(circuitBreaker))
        .test(1)
        .cancel();

    then(circuitBreaker).should(never()).releasePermission();
    then(circuitBreaker).should(never())
        .onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
    then(circuitBreaker).should().onSuccess(anyLong(), any(TimeUnit.class));
}
 
Example #24
Source File: TimeLimiterTransformerPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timeoutEmpty() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestSubscriber<Object> subscriber = Flowable.empty()
        .delay(1, TimeUnit.MINUTES)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    subscriber.assertError(TimeoutException.class);
    then(timeLimiter).should()
        .onError(any(TimeoutException.class));
}
 
Example #25
Source File: FlowableRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitSingleEventWithSinglePermit() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Flowable.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertResult(1);
}
 
Example #26
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 #27
Source File: ReactiveBatchProcessorV3.java    From code-examples with MIT License 5 votes vote down vote up
public void start() {
  // WARNING: this code doesn't work as expected
  Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize);

  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(scheduler))
      .subscribeWith(new SimpleSubscriber<>(threads, 1));
}
 
Example #28
Source File: ReplayingShareFlowableTest.java    From RxReplayingShare with Apache License 2.0 5 votes vote down vote up
@Test public void initialValueToNewSubscriber() {
  PublishProcessor<String> subject = PublishProcessor.create();
  Flowable<String> flowable = subject.compose(ReplayingShare.<String>instance());

  TestSubscriber<String> subscriber1 = new TestSubscriber<>();
  flowable.subscribe(subscriber1);
  subscriber1.assertNoValues();

  subject.onNext("Foo");
  subscriber1.assertValues("Foo");

  TestSubscriber<String> subscriber2 = new TestSubscriber<>();
  flowable.subscribe(subscriber2);
  subscriber2.assertValues("Foo");
}
 
Example #29
Source File: FlowableRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitAllEvents() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Flowable.fromArray(1, 2)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertResult(1, 2);
}
 
Example #30
Source File: JAXRSRxJava3FlowableTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHelloWorldAsyncObservable() throws Exception {
    String address = "http://localhost:" + PORT + "/rx3/flowable/textAsync";
    WebClient wc = WebClient.create(address,
                                    Collections.singletonList(new FlowableRxInvokerProvider()));
    Flowable<String> obs = wc.accept("text/plain")
        .rx(FlowableRxInvoker.class)
        .get(String.class);

    final TestSubscriber<String> subscriber = new TestSubscriber<>();
    obs.map(s -> s + s).subscribe(subscriber);
    
    subscriber.await(2, TimeUnit.SECONDS);
    subscriber.assertResult("Hello, world!Hello, world!");
}