io.reactivex.rxjava3.core.Scheduler Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Scheduler. 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: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link ObservableTransformer} that will flatten the provided {@link Action} into the
 * stream as a {@link Completable} every time it receives an effect from the upstream effects
 * observable. This Completable will be subscribed on the specified {@link Scheduler}. This will
 * result in calling the provided Action on the specified scheduler every time an effect is
 * dispatched to the created effect transformer.
 *
 * @param doEffect the {@link Action} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} that the action should be run on
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return an {@link ObservableTransformer} that can be used with a {@link
 *     RxMobius.SubtypeEffectHandlerBuilder}.
 */
static <F, E> ObservableTransformer<F, E> fromAction(
    final Action doEffect, @Nullable final Scheduler scheduler) {
  return new ObservableTransformer<F, E>() {
    @Override
    public ObservableSource<E> apply(Observable<F> effectStream) {
      return effectStream
          .flatMapCompletable(
              new Function<F, CompletableSource>() {
                @Override
                public CompletableSource apply(F f) throws Exception {
                  return scheduler == null
                      ? Completable.fromAction(doEffect)
                      : Completable.fromAction(doEffect).subscribeOn(scheduler);
                }
              })
          .toObservable();
    }
  };
}
 
Example #2
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link ObservableTransformer} that will flatten the provided {@link Consumer} into
 * the stream as a {@link Completable} every time it receives an effect from the upstream effects
 * observable. This will result in calling the consumer on the specified scheduler, and passing it
 * the requested effect object.
 *
 * @param doEffect the {@link Consumer} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} to be used when invoking the consumer
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return an {@link ObservableTransformer} that can be used with a {@link
 *     RxMobius.SubtypeEffectHandlerBuilder}.
 */
static <F, E> ObservableTransformer<F, E> fromConsumer(
    final Consumer<F> doEffect, @Nullable final Scheduler scheduler) {
  return new ObservableTransformer<F, E>() {
    @Override
    public ObservableSource<E> apply(Observable<F> effectStream) {
      return effectStream
          .flatMapCompletable(
              new Function<F, CompletableSource>() {
                @Override
                public CompletableSource apply(final F effect) {
                  Completable completable =
                      Completable.fromAction(
                          new Action() {
                            @Override
                            public void run() throws Throwable {
                              doEffect.accept(effect);
                            }
                          });
                  return scheduler == null ? completable : completable.subscribeOn(scheduler);
                }
              })
          .toObservable();
    }
  };
}
 
Example #3
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link ObservableTransformer} that will flatten the provided {@link Function} into
 * the stream as an {@link Observable} every time it receives an effect from the upstream effects
 * observable. This will result in calling the function on the specified scheduler, and passing it
 * the requested effect object then emitting its returned value.
 *
 * @param function the {@link Function} to be invoked every time the effect is requested
 * @param scheduler the {@link Scheduler} to be used when invoking the function
 * @param <F> the type of Effect this transformer handles
 * @param <E> the type of Event this transformer emits
 * @return an {@link ObservableTransformer} that can be used with a {@link
 *     RxMobius.SubtypeEffectHandlerBuilder}.
 */
static <F, E> ObservableTransformer<F, E> fromFunction(
    final Function<F, E> function, @Nullable final Scheduler scheduler) {
  return new ObservableTransformer<F, E>() {
    @Override
    public ObservableSource<E> apply(Observable<F> effectStream) {
      return effectStream.flatMap(
          new Function<F, ObservableSource<E>>() {
            @Override
            public ObservableSource<E> apply(@NonNull F f) {
              Observable<E> eventObservable =
                  Observable.fromSupplier(
                      new Supplier<E>() {
                        @Override
                        public E get() throws Throwable {
                          return function.apply(f);
                        }
                      });
              return scheduler == null ? eventObservable : eventObservable.subscribeOn(scheduler);
            }
          });
    }
  };
}
 
Example #4
Source File: ReplayRelay.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {
    if (maxSize <= 0) {
        throw new IllegalArgumentException("maxSize > 0 required but it was " + maxSize);
    }
    if (maxAge <= 0) {
        throw new IllegalArgumentException("maxAge > 0 required but it was " + maxAge);
    }
    if (unit == null) throw new NullPointerException("unit == null");
    if (scheduler == null) throw new NullPointerException("scheduler == null");
    this.maxSize = maxSize;
    this.maxAge = maxAge;
    this.unit = unit;
    this.scheduler = scheduler;
    TimedNode<T> h = new TimedNode<T>(null, 0L);
    this.tail = h;
    this.head = h;
}
 
Example #5
Source File: ReplayRelay.java    From RxRelay with Apache License 2.0 6 votes vote down vote up
SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {
    if (maxSize <= 0) {
        throw new IllegalArgumentException("maxSize > 0 required but it was " + maxSize);
    }
    if (maxAge <= 0) {
        throw new IllegalArgumentException("maxAge > 0 required but it was " + maxAge);
    }
    if (unit == null) throw new NullPointerException("unit == null");
    if (scheduler == null) throw new NullPointerException("scheduler == null");
    this.maxSize = maxSize;
    this.maxAge = maxAge;
    this.unit = unit;
    this.scheduler = scheduler;
    TimedNode<T> h = new TimedNode<T>(null, 0L);
    this.tail = h;
    this.head = h;
}
 
Example #6
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 #7
Source File: ReactiveBatchProcessor.java    From code-examples with MIT License 5 votes vote down vote up
void start() {

    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(m)
            .map(messageHandler::handleMessage))
            .subscribeOn(scheduler))
        .subscribeWith(new SimpleSubscriber<>(threads, 1));
  }
 
Example #8
Source File: ReactiveBatchProcessor.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),
      new WaitForCapacityPolicy()
  ));
}
 
Example #9
Source File: ReactiveBatchProcessorV1.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)
  ));
}
 
Example #10
Source File: ReactiveBatchProcessorV3.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)
  ));
}
 
Example #11
Source File: Rx3Idler.java    From RxIdler with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps the supplied {@link Scheduler} into one which also implements {@link IdlingResource}.
 * You must {@linkplain IdlingRegistry#register(IdlingResource...) register} the
 * returned instance with Espresso before it will be used. Only work scheduled on the returned
 * instance directly will be registered.
 */
@SuppressWarnings("ConstantConditions") // Public API guarding.
@CheckResult @NonNull
public static IdlingResourceScheduler wrap(@NonNull Scheduler scheduler, @NonNull String name) {
  if (scheduler == null) throw new NullPointerException("scheduler == null");
  if (name == null) throw new NullPointerException("name == null");
  return new DelegatingIdlingResourceScheduler(scheduler, name);
}
 
Example #12
Source File: Rx3Idler.java    From RxIdler with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a function which wraps the supplied {@link Scheduler} in one which notifies Espresso as
 * to whether it is currently executing work or not.
 * <p>
 * Note: Work scheduled in the future does not mark the idling resource as busy.
 */
@SuppressWarnings("ConstantConditions") // Public API guarding.
@CheckResult @NonNull
public static Function<Supplier<Scheduler>, Scheduler> create(@NonNull final String name) {
  if (name == null) throw new NullPointerException("name == null");
  return delegate -> {
    IdlingResourceScheduler scheduler =
        new DelegatingIdlingResourceScheduler(delegate.get(), name);
    IdlingRegistry.getInstance().register(scheduler);
    return scheduler;
  };
}
 
Example #13
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 5 votes vote down vote up
@Test public void betweenPeriodicSchedulesReportsIdle() {
  Scheduler.Worker worker = scheduler.createWorker();
  CountingRunnable action = new CountingRunnable();
  worker.schedulePeriodically(action, 0, 1, SECONDS);
  delegate.triggerActions();
  assertEquals(1, action.count());
  delegate.advanceTimeBy(500, MILLISECONDS);
  assertIdle(1);
  delegate.advanceTimeBy(1000, MILLISECONDS);
  assertIdle(2);
}
 
Example #14
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)
  ));
}
 
Example #15
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 5 votes vote down vote up
@Test public void unsubscribingScheduledWorkWhileRunningWorkReportsBusy() {
  final Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(() -> {
    worker.dispose();
    assertBusy();
  });
  delegate.triggerActions();
}
 
Example #16
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
@Test public void finishingWorkWithoutRegisteredCallbackDoesNotCrash() {
  IdlingResourceScheduler scheduler = Rx3Idler.wrap(delegate, "Bob");
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new CountingRunnable());
  delegate.triggerActions();
}
 
Example #17
Source File: MainService.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) {
    final Scheduler contextAwareScheduler = Schedulers.from(ctx.contextAwareExecutor());

    // This logic mimics using a blocking method, which would usually be something like a MySQL
    // database query using JDBC.
    final Flowable<Long> fetchNumsFromFakeDb =
            Single.fromCallable(
                    () -> {
                        // The context is mounted in a thread-local, meaning it is available to all
                        // logic such as tracing.
                        checkState(ServiceRequestContext.current() == ctx);
                        checkState(!ctx.eventLoop().inEventLoop());

                        Uninterruptibles.sleepUninterruptibly(Duration.ofMillis(50));
                        return ImmutableList.of(23L, -23L);
                    })
                  // Always run blocking logic on the blocking task executor. By using
                  // ServiceRequestContext.blockingTaskExecutor, you also ensure the context is mounted
                  // inside the logic (e.g., your DB call will be traced!).
                  .subscribeOn(Schedulers.from(ctx.blockingTaskExecutor()))
                  .flattenAsFlowable(l -> l);

    final Flowable<Long> extractNumsFromRequest =
            Single.fromCompletionStage(req.aggregate())
                           // Unless you know what you're doing, always use subscribeOn with the context
                           // executor to have the context mounted and stay on a single thread to reduce
                           // concurrency issues.
                           .subscribeOn(contextAwareScheduler)
                           .flatMapPublisher(request -> {
                               // The context is mounted in a thread-local, meaning it is available to all
                               // logic such as tracing.
                               checkState(ServiceRequestContext.current() == ctx);
                               checkState(ctx.eventLoop().inEventLoop());

                               final List<Long> nums = new ArrayList<>();
                               for (String token : Iterables.concat(
                                       NUM_SPLITTER.split(request.path().substring(1)),
                                       NUM_SPLITTER.split(request.contentUtf8()))) {
                                   nums.add(Long.parseLong(token));
                               }

                               return Flowable.fromIterable(nums);
                           });

    final Single<HttpResponse> response =
            Flowable.concatArrayEager(extractNumsFromRequest, fetchNumsFromFakeDb)
                    // Unless you know what you're doing, always use subscribeOn with the context executor
                    // to have the context mounted and stay on a single thread to reduce concurrency issues.
                    .subscribeOn(contextAwareScheduler)
                    // When concatenating flowables, you should almost always call observeOn with the
                    // context executor because we don't know here whether the subscription is on it or
                    // something like a blocking task executor.
                    .observeOn(contextAwareScheduler)
                    .flatMapSingle(num -> {
                        // The context is mounted in a thread-local, meaning it is available to all logic
                        // such as tracing.
                        checkState(ServiceRequestContext.current() == ctx);
                        checkState(ctx.eventLoop().inEventLoop());

                        return Single.fromCompletionStage(backendClient.get("/square/" + num).aggregate());
                    })
                    .map(AggregatedHttpResponse::contentUtf8)
                    .collectInto(new StringBuilder(), (current, item) -> current.append(item).append('\n'))
                    .map(content -> HttpResponse.of(content.toString()))
                    .onErrorReturn(HttpResponse::ofFailure);

    return HttpResponse.from(response.toCompletionStage());
}
 
Example #18
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
@Ignore("OOMs")
public void testEmissionSubscriptionRace() throws Exception {
    Scheduler s = Schedulers.io();
    Scheduler.Worker worker = Schedulers.io().createWorker();
    try {
        for (int i = 0; i < 50000; i++) {
            if (i % 1000 == 0) {
                System.out.println(i);
            }
            final BehaviorRelay<Object> rs = BehaviorRelay.create();

            final CountDownLatch finish = new CountDownLatch(1);
            final CountDownLatch start = new CountDownLatch(1);

            worker.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    rs.accept(1);
                }
            });

            final AtomicReference<Object> o = new AtomicReference<Object>();

            rs.subscribeOn(s).observeOn(Schedulers.io())
            .subscribe(new DefaultObserver<Object>() {

                @Override
                public void onComplete() {
                    o.set(-1);
                    finish.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    o.set(e);
                    finish.countDown();
                }

                @Override
                public void onNext(Object t) {
                    o.set(t);
                    finish.countDown();
                }

            });
            start.countDown();

            if (!finish.await(5, TimeUnit.SECONDS)) {
                System.out.println(o.get());
                System.out.println(rs.hasObservers());
                fail("Timeout @ " + i);
                break;
            } else {
                Assert.assertEquals(1, o.get());
            }
        }
    } finally {
        worker.dispose();
    }
}
 
Example #19
Source File: ReplayRelayConcurrencyTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
public void testReplayRelayEmissionSubscriptionRace() throws Exception {
    Scheduler s = Schedulers.io();
    Scheduler.Worker worker = Schedulers.io().createWorker();
    try {
        for (int i = 0; i < 50000; i++) {
            if (i % 1000 == 0) {
                System.out.println(i);
            }
            final ReplayRelay<Object> rs = ReplayRelay.create();

            final CountDownLatch finish = new CountDownLatch(1);
            final CountDownLatch start = new CountDownLatch(1);

            worker.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    rs.accept(1);
                }
            });

            final AtomicReference<Object> o = new AtomicReference<Object>();

            rs.subscribeOn(s).observeOn(Schedulers.io())
            .subscribe(new DefaultObserver<Object>() {

                @Override
                public void onComplete() {
                    o.set(-1);
                    finish.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    o.set(e);
                    finish.countDown();
                }

                @Override
                public void onNext(Object t) {
                    o.set(t);
                    finish.countDown();
                }

            });
            start.countDown();

            if (!finish.await(5, TimeUnit.SECONDS)) {
                System.out.println(o.get());
                System.out.println(rs.hasObservers());
                Assert.fail("Timeout @ " + i);
                break;
            } else {
                Assert.assertEquals(1, o.get());
            }
        }
    } finally {
        worker.dispose();
    }
}
 
Example #20
Source File: ReplayRelayBoundedConcurrencyTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
    public void testReplaySubjectEmissionSubscriptionRace() throws Exception {
        Scheduler s = Schedulers.io();
        Scheduler.Worker worker = Schedulers.io().createWorker();
        try {
            for (int i = 0; i < 50000; i++) {
                if (i % 1000 == 0) {
                    System.out.println(i);
                }
                final ReplayRelay<Object> rs = ReplayRelay.createWithSize(2);

                final CountDownLatch finish = new CountDownLatch(1);
                final CountDownLatch start = new CountDownLatch(1);

//                int j = i;

                worker.schedule(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            start.await();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
//                        System.out.println("> " + j);
                        rs.accept(1);
                    }
                });

                final AtomicReference<Object> o = new AtomicReference<Object>();

                rs
//                .doOnSubscribe(v -> System.out.println("!! " + j))
//                .doOnNext(e -> System.out.println(">> " + j))
                .subscribeOn(s)
                .observeOn(Schedulers.io())
//                .doOnNext(e -> System.out.println(">>> " + j))
                .subscribe(new DefaultObserver<Object>() {

                    @Override
                    protected void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onComplete() {
                        o.set(-1);
                        finish.countDown();
                    }

                    @Override
                    public void onError(Throwable e) {
                        o.set(e);
                        finish.countDown();
                    }

                    @Override
                    public void onNext(Object t) {
                        o.set(t);
                        finish.countDown();
                    }

                });
                start.countDown();

                if (!finish.await(5, TimeUnit.SECONDS)) {
                    System.out.println(o.get());
                    System.out.println(rs.hasObservers());
                    Assert.fail("Timeout @ " + i);
                    break;
                } else {
                    Assert.assertEquals(1, o.get());
                }
            }
        } finally {
            worker.dispose();
        }
    }
 
Example #21
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
@Ignore("OOMs")
public void testEmissionSubscriptionRace() throws Exception {
    Scheduler s = Schedulers.io();
    Scheduler.Worker worker = Schedulers.io().createWorker();
    try {
        for (int i = 0; i < 50000; i++) {
            if (i % 1000 == 0) {
                System.out.println(i);
            }
            final BehaviorRelay<Object> rs = BehaviorRelay.create();

            final CountDownLatch finish = new CountDownLatch(1);
            final CountDownLatch start = new CountDownLatch(1);

            worker.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    rs.accept(1);
                }
            });

            final AtomicReference<Object> o = new AtomicReference<Object>();

            rs.subscribeOn(s).observeOn(Schedulers.io())
            .subscribe(new DefaultObserver<Object>() {

                @Override
                public void onComplete() {
                    o.set(-1);
                    finish.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    o.set(e);
                    finish.countDown();
                }

                @Override
                public void onNext(Object t) {
                    o.set(t);
                    finish.countDown();
                }

            });
            start.countDown();

            if (!finish.await(5, TimeUnit.SECONDS)) {
                System.out.println(o.get());
                System.out.println(rs.hasObservers());
                fail("Timeout @ " + i);
                break;
            } else {
                Assert.assertEquals(1, o.get());
            }
        }
    } finally {
        worker.dispose();
    }
}
 
Example #22
Source File: ReplayRelayConcurrencyTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
public void testReplayRelayEmissionSubscriptionRace() throws Exception {
    Scheduler s = Schedulers.io();
    Scheduler.Worker worker = Schedulers.io().createWorker();
    try {
        for (int i = 0; i < 50000; i++) {
            if (i % 1000 == 0) {
                System.out.println(i);
            }
            final ReplayRelay<Object> rs = ReplayRelay.create();

            final CountDownLatch finish = new CountDownLatch(1);
            final CountDownLatch start = new CountDownLatch(1);

            worker.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    rs.accept(1);
                }
            });

            final AtomicReference<Object> o = new AtomicReference<Object>();

            rs.subscribeOn(s).observeOn(Schedulers.io())
            .subscribe(new DefaultObserver<Object>() {

                @Override
                public void onComplete() {
                    o.set(-1);
                    finish.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    o.set(e);
                    finish.countDown();
                }

                @Override
                public void onNext(Object t) {
                    o.set(t);
                    finish.countDown();
                }

            });
            start.countDown();

            if (!finish.await(5, TimeUnit.SECONDS)) {
                System.out.println(o.get());
                System.out.println(rs.hasObservers());
                Assert.fail("Timeout @ " + i);
                break;
            } else {
                Assert.assertEquals(1, o.get());
            }
        }
    } finally {
        worker.dispose();
    }
}
 
Example #23
Source File: ReplayRelayBoundedConcurrencyTest.java    From RxRelay with Apache License 2.0 4 votes vote down vote up
@Test
    public void testReplaySubjectEmissionSubscriptionRace() throws Exception {
        Scheduler s = Schedulers.io();
        Scheduler.Worker worker = Schedulers.io().createWorker();
        try {
            for (int i = 0; i < 50000; i++) {
                if (i % 1000 == 0) {
                    System.out.println(i);
                }
                final ReplayRelay<Object> rs = ReplayRelay.createWithSize(2);

                final CountDownLatch finish = new CountDownLatch(1);
                final CountDownLatch start = new CountDownLatch(1);

//                int j = i;

                worker.schedule(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            start.await();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
//                        System.out.println("> " + j);
                        rs.accept(1);
                    }
                });

                final AtomicReference<Object> o = new AtomicReference<Object>();

                rs
//                .doOnSubscribe(v -> System.out.println("!! " + j))
//                .doOnNext(e -> System.out.println(">> " + j))
                .subscribeOn(s)
                .observeOn(Schedulers.io())
//                .doOnNext(e -> System.out.println(">>> " + j))
                .subscribe(new DefaultObserver<Object>() {

                    @Override
                    protected void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onComplete() {
                        o.set(-1);
                        finish.countDown();
                    }

                    @Override
                    public void onError(Throwable e) {
                        o.set(e);
                        finish.countDown();
                    }

                    @Override
                    public void onNext(Object t) {
                        o.set(t);
                        finish.countDown();
                    }

                });
                start.countDown();

                if (!finish.await(5, TimeUnit.SECONDS)) {
                    System.out.println(o.get());
                    System.out.println(rs.hasObservers());
                    Assert.fail("Timeout @ " + i);
                    break;
                } else {
                    Assert.assertEquals(1, o.get());
                }
            }
        } finally {
            worker.dispose();
        }
    }
 
Example #24
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
@Test public void unsubscribingScheduledWorksReportsIdle() {
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new CountingRunnable());
  worker.dispose();
  assertIdle(1);
}
 
Example #25
Source File: SchedulerWorkRunner.java    From mobius with Apache License 2.0 4 votes vote down vote up
public SchedulerWorkRunner(@NonNull Scheduler scheduler) {
  this.worker = checkNotNull(scheduler).createWorker();
}
 
Example #26
Source File: Catnip.java    From catnip with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nonnull
@CheckReturnValue
default Scheduler rxScheduler() {
    return options().rxScheduler();
}
 
Example #27
Source File: DelegatingIdlingResourceScheduler.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
DelegatingIdlingResourceScheduler(Scheduler delegate, String name) {
  this.delegate = delegate;
  this.name = name;
}
 
Example #28
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
@Test public void scheduledWorkReportsBusy() {
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new CountingRunnable());
  assertBusy();
}
 
Example #29
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
@Test public void scheduledWorkUnsubscribedReportsIdle() {
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new CountingRunnable()).dispose();
  assertIdle(1);
}
 
Example #30
Source File: DelegatingIdlingResourceSchedulerTest.java    From RxIdler with Apache License 2.0 4 votes vote down vote up
@Test public void scheduleWithZeroDelayReportsBusy() {
  Scheduler.Worker worker = scheduler.createWorker();
  worker.schedule(new CountingRunnable(), 0, SECONDS);
  assertBusy();
}