rx.schedulers.TestScheduler Java Examples

The following examples show how to use rx.schedulers.TestScheduler. 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: OperatorSampleFirstTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleWindowIsConstantDuration() {
    @SuppressWarnings("unchecked")
    Observer<Integer> observer = mock(Observer.class);
    TestScheduler s = new TestScheduler();
    PublishSubject<Integer> o = PublishSubject.create();
    o.compose(Transformers.<Integer> sampleFirst(1000, TimeUnit.MILLISECONDS, s))
            .subscribe(observer);

    // send events with simulated time increments
    s.advanceTimeTo(0, TimeUnit.MILLISECONDS);
    o.onNext(1);
    s.advanceTimeTo(1200, TimeUnit.MILLISECONDS);
    o.onNext(2);
    s.advanceTimeTo(2100, TimeUnit.MILLISECONDS);
    o.onNext(3);
    o.onCompleted();

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer).onNext(1);
    inOrder.verify(observer).onNext(2);
    inOrder.verify(observer).onNext(3);
    inOrder.verify(observer).onCompleted();
    inOrder.verifyNoMoreInteractions();
}
 
Example #2
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenThrottlingLast_thenThrottleLastItemsAreEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.throttleLast(3100L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(4, 6);
}
 
Example #3
Source File: MulticastEventStreamClientTest.java    From MarketData with Apache License 2.0 6 votes vote down vote up
@Test
public void Should_transmit_events_from_the_target_client() {
    // given
    TestScheduler scheduler = Schedulers.test();
    PublishSubject<String> subject = PublishSubject.create();
    EventStreamClient targetClient = mock(EventStreamClient.class);
    when(targetClient.readServerSideEvents()).thenReturn(subject);
    MulticastEventStreamClient multicastEventStreamClient = new MulticastEventStreamClient(targetClient, scheduler);
    Observable<String> events = multicastEventStreamClient.readServerSideEvents();
    // when
    TestSubscriber<String> subscriber = new TestSubscriber<>();
    events.subscribe(subscriber);
    subject.onNext("Hello!");
    // then
    assertThat(subscriber.getOnNextEvents()).hasSize(1).contains("Hello!");
}
 
Example #4
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenRangeObservable_whenThrottlingFirst_thenThrottledFirstItemsAreEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable =
            timedObservable.throttleFirst(4100L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(1, 6);
}
 
Example #5
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenSampling_thenOnlySampleItemsAreEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> sampledObservable =
            timedObservable.sample(2500L, TimeUnit.MILLISECONDS, testScheduler);

    sampledObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValues(3, 5, 6);
}
 
Example #6
Source File: DefaultEventBusTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotBufferEventsBeforeSubscribe() throws Exception {
    TestScheduler testScheduler = Schedulers.test();
    EventBus eventBus = new DefaultEventBus(testScheduler);

    TestSubscriber<CouchbaseEvent> subscriber = new TestSubscriber<CouchbaseEvent>();


    CouchbaseEvent event1 = mock(CouchbaseEvent.class);
    CouchbaseEvent event2 = mock(CouchbaseEvent.class);

    eventBus.publish(event1);
    assertFalse(eventBus.hasSubscribers());
    eventBus.get().subscribe(subscriber);
    assertTrue(eventBus.hasSubscribers());
    eventBus.publish(event2);

    testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);

    assertEquals(1, subscriber.getOnNextEvents().size());
    assertEquals(0, subscriber.getOnErrorEvents().size());
    assertEquals(0, subscriber.getOnCompletedEvents().size());
}
 
Example #7
Source File: DefaultEventBusTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishToSubscriber() throws Exception {
    TestScheduler testScheduler = Schedulers.test();
    EventBus eventBus = new DefaultEventBus(testScheduler);

    TestSubscriber<CouchbaseEvent> subscriber = new TestSubscriber<CouchbaseEvent>();
    assertFalse(eventBus.hasSubscribers());
    eventBus.get().subscribe(subscriber);
    assertTrue(eventBus.hasSubscribers());

    CouchbaseEvent event1 = mock(CouchbaseEvent.class);
    CouchbaseEvent event2 = mock(CouchbaseEvent.class);

    eventBus.publish(event1);
    eventBus.publish(event2);

    testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);

    assertEquals(2, subscriber.getOnNextEvents().size());
    assertEquals(0, subscriber.getOnErrorEvents().size());
    assertEquals(0, subscriber.getOnCompletedEvents().size());
}
 
Example #8
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenThrottlingWithTimeout_thenLastItemIsEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.throttleWithTimeout(2000L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValue(6);
}
 
Example #9
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenDebounceOperatorIsApplied_thenLastItemIsEmitted() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.debounce(2000L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertCompleted();
    subscriber.assertNoErrors();
    subscriber.assertValue(6);
}
 
Example #10
Source File: AwsObservableExtTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void asyncActionCompletable() throws Exception {
    AmazonWebServiceRequest someRequest = AmazonWebServiceRequest.NOOP;
    final MockAsyncClient<AmazonWebServiceRequest, String> client = new MockAsyncClient<>(someRequest, "some response");
    final Completable completable = AwsObservableExt.asyncActionCompletable(factory -> client.someAsyncOperation(factory.handler(
            (req, resp) -> {
                assertEquals(someRequest, req);
                assertEquals("some response", resp);
            },
            (t) -> {
                throw new IllegalStateException("Should never be here");
            }
    )));

    TestScheduler testScheduler = Schedulers.test();
    final AssertableSubscriber<Void> subscriber = completable.subscribeOn(testScheduler).test();

    testScheduler.triggerActions();
    subscriber.assertNotCompleted();

    client.run();
    testScheduler.triggerActions();
    subscriber.assertCompleted();
}
 
Example #11
Source File: RxJavaTimeFilteringOperatorsIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimedObservable_whenUsingTimeout_thenTimeOutException() {

    TestScheduler testScheduler = new TestScheduler();

    Observable<Integer> timedObservable =
            Observable.just(1, 2, 3, 4, 5, 6)
                    .zipWith(
                            Observable.interval(0, 1, TimeUnit.SECONDS, testScheduler),
                            (item, time) -> item
                    );

    TestSubscriber<Integer> subscriber = new TestSubscriber();

    Observable<Integer> filteredObservable = timedObservable.timeout(500L, TimeUnit.MILLISECONDS, testScheduler);

    filteredObservable.subscribe(subscriber);

    testScheduler.advanceTimeBy(7, TimeUnit.SECONDS);

    subscriber.assertError(TimeoutException.class);
    subscriber.assertValues(1);
}
 
Example #12
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithScheduler() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(RetryWhen.maxRetries(2).action(log)
                    .exponentialBackoff(1, TimeUnit.MINUTES).scheduler(scheduler).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertNotCompleted();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotCompleted();
    // next wait is 2 seconds so advancing by 1 should do nothing
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotCompleted();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2, 1, 2);
    ts.assertError(ex);
}
 
Example #13
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRetryWhenSpecificExceptionFails() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(RetryWhen.maxRetries(2).action(log)
                    .exponentialBackoff(1, TimeUnit.MINUTES).scheduler(scheduler)
                    .failWhenInstanceOf(IllegalArgumentException.class).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertError(ex);
}
 
Example #14
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRetryWhenSpecificExceptionFailsBecauseIsNotInstanceOf() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(RetryWhen.maxRetries(2).action(log)
                    .exponentialBackoff(1, TimeUnit.MINUTES).scheduler(scheduler)
                    .retryWhenInstanceOf(SQLException.class).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertError(ex);
}
 
Example #15
Source File: AwsObservableExtTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void asyncActionSingle() throws Exception {
    AmazonWebServiceRequest someRequest = AmazonWebServiceRequest.NOOP;
    final MockAsyncClient<AmazonWebServiceRequest, String> client = new MockAsyncClient<>(someRequest, "some response");
    Single<String> single = AwsObservableExt.asyncActionSingle(supplier -> client.someAsyncOperation(supplier.handler()));

    TestScheduler testScheduler = Schedulers.test();
    final AssertableSubscriber<String> subscriber = single.subscribeOn(testScheduler).test();

    testScheduler.triggerActions();
    subscriber.assertNoValues();
    subscriber.assertNotCompleted();

    client.run();
    testScheduler.triggerActions();
    subscriber.assertValueCount(1);
    subscriber.assertValue("some response");
    subscriber.assertCompleted();
}
 
Example #16
Source File: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testByteBufReleaseWithTimeout() throws Exception {
    TestScheduler testScheduler = Schedulers.test();
    UnicastAutoReleaseSubject<ByteBuf> subject = UnicastAutoReleaseSubject.create(100, TimeUnit.MILLISECONDS,
            testScheduler);
    ByteBuf buffer = Unpooled.buffer();

    subject.onNext(buffer);
    Assert.assertEquals("Byte buffer not retained on buffering by subject.", 1, buffer.refCnt());

    subject.onCompleted();


    testScheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS);
    Assert.assertEquals("Byte buffer not fully released", 0, buffer.refCnt());
}
 
Example #17
Source File: TransformersTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelayWithPlayRate() {
    TestSubscriber<Object> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Integer, Long> time = new Func1<Integer, Long>() {

        @Override
        public Long call(Integer t) {
            return (long) t;
        }
    };
    Observable //
            .just(1, 2, 3) //
            .compose(Transformers.delay(time, Functions.constant0(0.001), 0, scheduler)) //
            .subscribe(ts);
    ts.assertNoValues();
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValue(1);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 2);
    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 2, 3);
    ts.assertCompleted();
}
 
Example #18
Source File: UnicastAutoReleaseSubjectTest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testTraceIdAppearsWhenNoSubscription() throws Exception {
    TestScheduler testScheduler = Schedulers.test();
    OnUnsubscribeAction onUnsub = new OnUnsubscribeAction();
    UnicastAutoReleaseSubject<String> subject = UnicastAutoReleaseSubject.create(1, TimeUnit.DAYS, testScheduler,
            onUnsub);
    subject.withTraceIdentifier("noSub");
    subject.onNext("Start the timeout now."); // Since the timeout is scheduled only after content arrival.
    testScheduler.advanceTimeBy(1, TimeUnit.DAYS);
    try {
        subject.toBlocking().last(); // Should immediately throw an error.
        fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
        assertThat(e).hasMessageStartingWith("The content of this Observable (noSub)");
    }
}
 
Example #19
Source File: AptoideBiAnalyticsTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void logNotTimeReached() throws Exception {
  AptoideBiEventService aptoideBiEventService = mock(AptoideBiEventService.class);
  EventsPersistence eventPersistenceMock = mock(EventsPersistence.class);
  SessionPersistence sessionPersistence = mock(SessionPersistence.class);
  CrashLogger crashReport = mock(CrashLogger.class);
  AnalyticsLogger debugLogger = mock(AnalyticsLogger.class);
  String eventName = "test event";
  String context = "test context";
  Map<String, Object> data = new HashMap<>();
  Event event = new Event(eventName, data, AnalyticsManager.Action.OPEN, context, 0);
  TestScheduler scheduler = Schedulers.test();
  AptoideBiAnalytics analytics =
      new AptoideBiAnalytics(eventPersistenceMock, sessionPersistence, aptoideBiEventService,
          new CompositeSubscription(), scheduler, 200000, 20000, crashReport, debugLogger);
  when(aptoideBiEventService.send(any())).thenReturn(Completable.complete());
  List<Event> eventList = setupPersistence(eventPersistenceMock);
  analytics.setup();
  Thread.sleep(19);
  analytics.log(event.getEventName(), event.getData(), event.getAction(), event.getContext());
  scheduler.advanceTimeBy(1, TimeUnit.SECONDS);

  verify(aptoideBiEventService, times(0)).send(any());
  verify(eventPersistenceMock, times(1)).save(Matchers.<Event>any());
  Assert.assertEquals(1, eventList.size());
}
 
Example #20
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRetryWhenSpecificExceptionAllowed() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(RetryWhen.maxRetries(2).action(log)
                    .exponentialBackoff(1, TimeUnit.MINUTES).scheduler(scheduler)
                    .retryWhenInstanceOf(IllegalArgumentException.class).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertNotCompleted();
}
 
Example #21
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryWhenSpecificExceptionAllowedUsePredicateReturnsTrue() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Throwable, Boolean> predicate = new Func1<Throwable, Boolean>() {
        @Override
        public Boolean call(Throwable t) {
            return t instanceof IllegalArgumentException;
        }
    };
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(
                    RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES)
                            .scheduler(scheduler).retryIf(predicate).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertNotCompleted();
}
 
Example #22
Source File: ScanReplay.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpectedReplayBehavior() {
    final TestScheduler scheduler = new TestScheduler();
    final TestSubject<Integer> subject = TestSubject.create(scheduler);
    final TestSubscriber<Integer> subscriber = new TestSubscriber<>();

    final ConnectableObservable<Integer> sums = subject.scan((a, b) -> a + b).replay(1);
    sums.connect();

    subject.onNext(1);
    subject.onNext(2);
    subject.onNext(3);
    scheduler.triggerActions();

    sums.subscribe(subscriber);

    subscriber.assertValueCount(1);
    subscriber.assertValues(6);
}
 
Example #23
Source File: ScanReplay.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
    public void testFlakyReplayBehavior() {
        final TestScheduler scheduler = new TestScheduler();
        final TestSubject<Integer> subject = TestSubject.create(scheduler);
        final TestSubscriber<Integer> subscriber = new TestSubscriber<>();

        final ConnectableObservable<Integer> sums = subject.scan(1, (a, b) -> a + b).replay(1);
        sums.connect();

        subject.onNext(2);
        subject.onNext(3);
        scheduler.triggerActions();

        sums.subscribe(subscriber);

//        subscriber.assertValueCount(1);
        subscriber.assertValues(6);
    }
 
Example #24
Source File: Example16Test.java    From AnDevCon-RxPatterns with Apache License 2.0 6 votes vote down vote up
@Test
public void should_test_observable_interval() {
    TestScheduler scheduler = new TestScheduler();
    final List<Long> result = new ArrayList<>();
    Observable.interval(1, TimeUnit.SECONDS, scheduler)
            .take(5)
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                    result.add(aLong);
                }
            });
    assertTrue(result.isEmpty());
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    assertEquals(2, result.size());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    assertEquals(5, result.size());
}
 
Example #25
Source File: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryWhenSpecificExceptionAllowedUsePredicateReturnsFalse() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Throwable, Boolean> predicate = Functions.alwaysFalse();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(
                    RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES)
                            .scheduler(scheduler).retryIf(predicate).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertError(ex);
}
 
Example #26
Source File: RestartableSetTest.java    From satellite with MIT License 6 votes vote down vote up
@Override
public Subscription invoke(DeliveryMethod method, TestSubscriber<Notification<Long>> testSubscriber, final TestScheduler scheduler, RestartableSet set) {
    return set
        .channel(RESTARTABLE_ID, method, new ObservableFactory<String, Long>() {
            @Override
            public Observable<Long> call(final String a) {
                return interval(1, 1, TimeUnit.SECONDS, scheduler).map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return aLong + Long.parseLong(a);
                    }
                });
            }
        })
        .subscribe(testSubscriber);
}
 
Example #27
Source File: ObsTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachedResetableScheduledReset() {
    TestScheduler scheduler = new TestScheduler();
    final AtomicInteger count = new AtomicInteger(0);
    Observable<Integer> o = Observable.defer(new Func0<Observable<Integer>>() {
        @Override
        public Observable<Integer> call() {
            return Observable.just(count.incrementAndGet());
        }
    });
    CloseableObservableWithReset<Integer> cached = Obs.cache(o, 5, TimeUnit.MINUTES, scheduler);
    assertEquals(1, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    assertEquals(1, (int) cached.observable().toBlocking().single());
    cached.reset();
    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);
    assertEquals(2, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    assertEquals(2, (int) cached.observable().toBlocking().single());
    cached.reset();
    assertEquals(2, (int) cached.observable().toBlocking().single());
    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);
    assertEquals(3, (int) cached.observable().toBlocking().single());
    cached.close();
}
 
Example #28
Source File: ObsTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachedScheduledReset() {
    TestScheduler scheduler = new TestScheduler();
    Worker worker = scheduler.createWorker();
    try {
        final AtomicInteger count = new AtomicInteger(0);
        Observable<Integer> source = Observable.defer(new Func0<Observable<Integer>>() {
            @Override
            public Observable<Integer> call() {
                return Observable.just(count.incrementAndGet());
            }
        })
                // cache
                .compose(Transformers.<Integer> cache(5, TimeUnit.MINUTES, worker));
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(3, TimeUnit.MINUTES);
        assertEquals(2, (int) source.toBlocking().single());
        assertEquals(2, (int) source.toBlocking().single());
    } finally {
        worker.unsubscribe();
    }
}
 
Example #29
Source File: MulticastEventStreamClientTest.java    From MarketData with Apache License 2.0 6 votes vote down vote up
/**
 * Test 21
 */
@Test
@Ignore
public void Should_generate_only_one_subscription_side_effect_with_multiple_subscribers() {
    // given
    Observable<String> source = Observable.create(subscriber -> {
        subscriber.onNext("open");
    });
    TestScheduler scheduler = Schedulers.test();
    EventStreamClient targetClient = mock(EventStreamClient.class);
    when(targetClient.readServerSideEvents()).thenReturn(source);
    MulticastEventStreamClient multicastEventStreamClient = new MulticastEventStreamClient(targetClient, scheduler);
    Observable<String> events = multicastEventStreamClient.readServerSideEvents();
    // when
    TestSubscriber<String> subscriber1 = new TestSubscriber<>();
    TestSubscriber<String> subscriber2 = new TestSubscriber<>();
    events.subscribe(subscriber1);
    events.subscribe(subscriber2);
    // then
    assertThat(subscriber1.getOnNextEvents()).hasSize(1);
    assertThat(subscriber2.getOnNextEvents()).isEmpty();
}
 
Example #30
Source File: OperatorSampleFirstTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void before() {
    scheduler = new TestScheduler();
    innerScheduler = scheduler.createWorker();
    observer = Mockito.mock(Observer.class);
}