io.reactivex.schedulers.TestScheduler Java Examples

The following examples show how to use io.reactivex.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: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMemberAvailableAfterCreationScheduledIsUsedImmediately() throws InterruptedException {
    TestScheduler ts = new TestScheduler();
    Scheduler s = createScheduleToDelayCreation(ts);
    AtomicInteger count = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .createRetryInterval(10, TimeUnit.MINUTES) //
            .maxSize(2) //
            .maxIdleTime(1, TimeUnit.HOURS) //
            .scheduler(s) //
            .build();
    List<Member<Integer>> list = new ArrayList<Member<Integer>>();
    pool.member().doOnSuccess(m -> list.add(m)).subscribe();
    assertEquals(0, list.size());
    ts.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.triggerActions();
    assertEquals(1, list.size());
    pool.member().doOnSuccess(m -> list.add(m)).subscribe();
    list.get(0).checkin();
    ts.triggerActions();
    assertEquals(2, list.size());
}
 
Example #2
Source File: Code04.java    From rxjava2-lab with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    TestScheduler scheduler = new TestScheduler();

    Single<Long> s1 = Single.timer(1, TimeUnit.SECONDS, scheduler);
    Single<String> s2 = Single.just("Hello");
    Single<String> r = Single.zip(s1, s2, (t, s) -> t + " -> " + s);

    TestObserver<String> testObserver = r.test();

    testObserver.assertNoValues();

    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    testObserver.assertNoValues();

    scheduler.advanceTimeBy(600, TimeUnit.MILLISECONDS);
    testObserver
            .assertNoErrors()
            .assertValue("0 -> Hello");
}
 
Example #3
Source File: AdamantApiWrapperSwitchOnFailureTest.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void before() {
    initStubs();

    counter = new AtomicInteger(0);
    scheduler = new TestScheduler();

    when(apiBuilder.build())
            .thenReturn(
                    Flowable.defer(() -> buildMockedApiWithErrorChatLoading(testNameRule.getMethodName())).toObservable()
            );
    when(keyGenerator.getKeyPairFromPassPhrase(TestConstants.TEST_PASS_PHRASE))
            .thenReturn(new KeyPair(TestConstants.TEST_PUBLIC_KEY, TestConstants.TEST_SECRET_KEY));

    wrapper = new AdamantApiWrapper(apiBuilder, keyGenerator, scheduler);

    Disposable subscribe = wrapper
            .authorize(TestConstants.TEST_PASS_PHRASE)
            .subscribe();
    subscritions.add(subscribe);

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
}
 
Example #4
Source File: ThrottleSampleTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    TestScheduler tsch = new TestScheduler();

    Flowable.fromArray(
            100,                // should emit 100 at T=100
            110, 120, 130, 150, // should emit 150 at T=200 
            250, 260,           // should emit 260 at T=300
            400                 // should emit 400 at T=400
    )
    .flatMap(v -> Flowable.timer(v, TimeUnit.MILLISECONDS, tsch).map(w -> v))
    .compose(throttleFirstSample(100, TimeUnit.MILLISECONDS, tsch))
    .subscribe(v -> System.out.println(v + " at T=" + tsch.now(TimeUnit.MILLISECONDS)));
    
    tsch.advanceTimeBy(1, TimeUnit.SECONDS);
}
 
Example #5
Source File: RxJavaDemoTest.java    From reactive-streams-in-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduler() {
    TestScheduler scheduler = new TestScheduler(); //1
    Observable<Long> tick = Observable
            .interval(1, TimeUnit.SECONDS, scheduler); //2
    Observable<String> observable =
            Observable.just("foo", "bar", "biz", "baz") //3
            .zipWith(tick, (string, index) -> index + "-" + string);//4
    TestObserver<String> testObserver = observable
            .subscribeOn(scheduler).test();//5

    scheduler.advanceTimeBy(2300, TimeUnit.MILLISECONDS);//6

    testObserver.assertNoErrors(); //7
    testObserver.assertValues("0-foo", "1-bar");
    testObserver.assertNotComplete();
}
 
Example #6
Source File: Modern_Testing.java    From Reactive-Programming-With-Java-9 with MIT License 6 votes vote down vote up
@Test
public void test_interval()
{
	TestScheduler testScheduler=new TestScheduler();
	Observable<Long>observable=Observable.interval(1, TimeUnit.SECONDS,testScheduler).take(5);
	TestObserver<Long> testObserver=new TestObserver<>();

	
	observable.subscribeOn(testScheduler).subscribe(testObserver);
	
	testObserver.assertNoValues();
	testObserver.assertNotComplete();
	testObserver.assertNoErrors();
	
	testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);
	testObserver.assertValueCount(1);
	testObserver.assertValues(0l);
	
	testScheduler.advanceTimeTo(6, TimeUnit.SECONDS);
	testObserver.assertValueCount(5);
	testObserver.assertValues(0l,1l,2l,3l,4l);
}
 
Example #7
Source File: SingleConcatTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
  TestScheduler testScheduler = new TestScheduler();

  final Single<List<Integer>> first = Single.timer(2, TimeUnit.SECONDS, testScheduler)
          .map(u -> Arrays.asList(1, 2, 3));
  final Single<List<Integer>> second = Single.just(Collections.emptyList());
  final Single<List<Integer>> third = Single.just(Collections.singletonList(4));
  final Single<List<Integer>> fourth = Single.just(Collections.singletonList(5));

  Single<List<Integer>> subject = Observable
    .fromIterable(Arrays.asList(first, second, third, fourth))
    .concatMapSingle(single -> single)
    .reduce(new ArrayList<>(), (seed, items) -> {
      seed.addAll(items);
      return seed;
    });

    TestObserver<List<Integer>> testObserver = subject.test();
    testScheduler.advanceTimeBy(3, TimeUnit.SECONDS);

    System.out.println(testObserver.values());
    testObserver.assertValue(list -> list.equals(Arrays.asList(1, 2, 3, 4, 5))); 
    // 5 is currently missing ; fourth was never subscribed in the first place
}
 
Example #8
Source File: ThrottleSampleTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void testObservable() {
    TestScheduler tsch = new TestScheduler();

    Observable.fromArray(
            100,                // should emit 100 at T=100
            110, 120, 130, 150, // should emit 150 at T=200 
            250, 260,           // should emit 260 at T=300
            400                 // should emit 400 at T=400
    )
    .flatMap(v -> Observable.timer(v, TimeUnit.MILLISECONDS, tsch).map(w -> v))
    .compose(throttleFirstSampleObservable(100, TimeUnit.MILLISECONDS, tsch))
    .subscribe(v -> System.out.println(v + " at T=" + tsch.now(TimeUnit.MILLISECONDS)));
    
    tsch.advanceTimeBy(1, TimeUnit.SECONDS);
}
 
Example #9
Source File: RxFlatmapAndSwitchmapUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() {
    //given
    List<String> actualOutput = new ArrayList<>();
    final TestScheduler scheduler = new TestScheduler();
    final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");

    //when
    Observable.fromIterable(keywordToSearch)
      .flatMap(s -> Observable
        .just(s + " FirstResult", s + " SecondResult")
        .delay(10, TimeUnit.SECONDS, scheduler))
      .toList()
      .doOnSuccess(s -> actualOutput.addAll(s))
      .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    //then
    assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult",
      "boo FirstResult", "boo SecondResult",
      "bo FirstResult", "bo SecondResult",
      "book FirstResult", "book SecondResult",
      "books FirstResult", "books SecondResult"));
}
 
Example #10
Source File: TransformersTest.java    From rxjava2-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertWithDelays() {
    TestScheduler s = new TestScheduler();
    TestSubscriber<Integer> ts = //
            Flowable.just(1).delay(1, TimeUnit.SECONDS, s) //
                    .concatWith(Flowable.just(2).delay(3, TimeUnit.SECONDS, s)) //
                    .compose(Transformers.insert(Maybe.just(3).delay(2, TimeUnit.SECONDS, s))) //
                    .test();
    ts.assertNoValues();
    s.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1);
    s.advanceTimeBy(2, TimeUnit.SECONDS);
    ts.assertValues(1, 3);
    s.advanceTimeBy(1, TimeUnit.SECONDS);
    ts.assertValues(1, 3, 2);
    ts.assertComplete();
}
 
Example #11
Source File: RetryWhenTest.java    From rxjava2-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();
    Predicate<Throwable> predicate = Predicates.alwaysFalse();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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 #12
Source File: RetryWhenTest.java    From rxjava2-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();
    Predicate<Throwable> predicate = new Predicate<Throwable>() {
        @Override
        public boolean test(Throwable t) {
            return t instanceof IllegalArgumentException;
        }
    };
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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.assertNotComplete();
}
 
Example #13
Source File: RxFlatmapAndSwitchmapUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() {
    //given
    List<String> actualOutput = new ArrayList<>();
    final TestScheduler scheduler = new TestScheduler();
    final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");

    //when
    Observable.fromIterable(keywordToSearch)
      .switchMap(s -> Observable
        .just(s + " FirstResult", s + " SecondResult")
        .delay(10, TimeUnit.SECONDS, scheduler))
      .toList()
      .doOnSuccess(s -> actualOutput.addAll(s))
      .subscribe();

    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    //then
    assertEquals(2, actualOutput.size());
    assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult"));
}
 
Example #14
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeWhenPoolClosedEmitsError() throws Exception {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger disposed = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> true) //
            .maxSize(3) //
            .maxIdleTime(1, TimeUnit.MINUTES) //
            .disposer(n -> disposed.incrementAndGet()) //
            .scheduler(s) //
            .build();
    pool.close();
    new FlowableSingleDeferUntilRequest<>( //
            pool.member()) //
                    .test(1) //
                    .assertError(PoolClosedException.class) //
                    .assertNoValues();
}
 
Example #15
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionPoolRecylesAlternating() {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> true) //
            .maxSize(2) //
            .maxIdleTime(1, TimeUnit.MINUTES) //
            .scheduler(s) //
            .build();
    TestSubscriber<Integer> ts = new FlowableSingleDeferUntilRequest<>(pool.member()) //
            .repeat() //
            .doOnNext(m -> m.checkin()) //
            .map(m -> m.value()) //
            .test(4); //
    s.triggerActions();
    ts.assertValueCount(4) //
            .assertNotTerminated();
    List<Object> list = ts.getEvents().get(0);
    // all 4 connections released were the same
    assertTrue(list.get(0) == list.get(1));
    assertTrue(list.get(1) == list.get(2));
    assertTrue(list.get(2) == list.get(3));
}
 
Example #16
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaxIdleTime() throws InterruptedException {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger disposed = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> true) //
            .maxSize(3) //
            .maxIdleTime(1, TimeUnit.MINUTES) //
            .disposer(n -> disposed.incrementAndGet()) //
            .scheduler(s) //
            .build();
    TestSubscriber<Member<Integer>> ts = new FlowableSingleDeferUntilRequest<>( //
            pool.member()) //
                    .doOnNext(m -> m.checkin()) //
                    .doOnNext(System.out::println) //
                    .doOnRequest(t -> System.out.println("test request=" + t)) //
                    .test(1);
    s.triggerActions();
    ts.assertValueCount(1);
    assertEquals(0, disposed.get());
    s.advanceTimeBy(1, TimeUnit.MINUTES);
    s.triggerActions();
    assertEquals(1, disposed.get());
}
 
Example #17
Source File: RetryWhenTest.java    From rxjava2-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();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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.assertNotComplete();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotComplete();
    // next wait is 2 seconds so advancing by 1 should do nothing
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2);
    ts.assertNotComplete();
    scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
    ts.assertValues(1, 2, 1, 2, 1, 2);
    ts.assertError(ex);
}
 
Example #18
Source File: RetryWhenTest.java    From rxjava2-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();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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 #19
Source File: RetryWhenTest.java    From rxjava2-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();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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 #20
Source File: RetryWhenTest.java    From rxjava2-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();
    Flowable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Flowable.<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.assertNotComplete();
}
 
Example #21
Source File: ThreadDumpTest.java    From AndroidGodEye with Apache License 2.0 6 votes vote down vote up
@Test
public void work2() {
    ((TestScheduler) ThreadUtil.computationScheduler()).advanceTimeBy(5, TimeUnit.SECONDS);
    try {
        TestObserver<List<ThreadInfo>> subscriber = new TestObserver<>();
        GodEye.instance().<ThreadDump, List<ThreadInfo>>moduleObservable(GodEye.ModuleName.THREAD).subscribe(subscriber);
        subscriber.assertValue(new Predicate<List<ThreadInfo>>() {
            @Override
            public boolean test(List<ThreadInfo> threadInfos) throws Exception {
                return threadInfos != null && !threadInfos.isEmpty();
            }
        });
    } catch (UninstallException e) {
        Assert.fail();
    }
}
 
Example #22
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscribeWithDisposedSubscription() throws Exception {
    TestScheduler s = new TestScheduler();
    AtomicInteger count = new AtomicInteger();
    AtomicInteger disposed = new AtomicInteger();
    Pool<Integer> pool = NonBlockingPool //
            .factory(() -> count.incrementAndGet()) //
            .healthCheck(n -> true) //
            .maxSize(3) //
            .maxIdleTime(1, TimeUnit.MINUTES) //
            .disposer(n -> disposed.incrementAndGet()) //
            .scheduler(s) //
            .build();
    AtomicInteger result = new AtomicInteger(0);
    pool.member().subscribe(new SingleObserver<Member<Integer>>() {

        @Override
        public void onSubscribe(Disposable d) {
            d.dispose();
        }

        @Override
        public void onSuccess(Member<Integer> t) {
            result.set(1);
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            result.set(2);
        }
    });
    assertEquals(0, result.get());
}
 
Example #23
Source File: BufferStartEndTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    TestScheduler scheduler = new TestScheduler();
    PublishProcessor<String> pp = PublishProcessor.create();

    Function<Flowable<String>, Flowable<List<String>>> f = o -> 
            o.buffer(o.filter(v -> v.contains("Start")), 
                     v -> Flowable.merge(o.filter(w -> w.contains("Start")), 
                                         Flowable.timer(5, TimeUnit.MINUTES, scheduler))); 

    pp.publish(f)
    .doOnNext(v -> {
        int s = v.size();
        if (s > 1 && v.get(s - 1).contains("Start")) {
            v.remove(s - 1);
        }
    })
    .subscribe(System.out::println);

    pp.onNext("Start");
    pp.onNext("A");
    pp.onNext("B");
    pp.onNext("End");

    pp.onNext("Start");
    pp.onNext("C");

    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);

    pp.onNext("Start");
    pp.onNext("D");
    pp.onNext("End");
    pp.onComplete();
}
 
Example #24
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolFactoryWhenFailsThenRecovers() {
    AtomicReference<Throwable> ex = new AtomicReference<>();
    Consumer<? super Throwable> handler = RxJavaPlugins.getErrorHandler();
    RxJavaPlugins.setErrorHandler(t -> ex.set(t));
    try {
        TestScheduler s = new TestScheduler();
        AtomicInteger c = new AtomicInteger();
        NonBlockingPool<Integer> pool = NonBlockingPool.factory(() -> {
            if (c.getAndIncrement() == 0) {
                throw new TestException();
            } else {
                return c.get();
            }
        }) //
                .maxSize(1) //
                .scheduler(s) //
                .createRetryInterval(10, TimeUnit.SECONDS) //
                .build();
        TestObserver<Integer> ts = pool.member() //
                .map(m -> m.value()) //
                .test() //
                .assertNotTerminated() //
                .assertNoValues();
        s.triggerActions();
        assertTrue(ex.get() instanceof UndeliverableException);
        assertTrue(((UndeliverableException) ex.get()).getCause() instanceof TestException);
        s.advanceTimeBy(10, TimeUnit.SECONDS);
        s.triggerActions();
        ts.assertComplete();
        ts.assertValue(2);
    } finally {
        RxJavaPlugins.setErrorHandler(handler);
    }
}
 
Example #25
Source File: NonBlockingPoolTest.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
private static Scheduler createScheduleToDelayCreation(TestScheduler ts) {
    return new Scheduler() {

        @Override
        public Worker createWorker() {
            Worker w = ts.createWorker();
            return new Worker() {

                @Override
                public void dispose() {
                    w.dispose();
                }

                @Override
                public boolean isDisposed() {
                    return w.isDisposed();
                }

                @Override
                public Disposable schedule(Runnable run, long delay, TimeUnit unit) {
                    if (run instanceof MemberSingle.Initializer && delay == 0) {
                        return w.schedule(run, 1, TimeUnit.MINUTES);
                    } else {
                        return w.schedule(run, delay, unit);
                    }
                }
            };
        }

    };
}
 
Example #26
Source File: TimeoutCancelv2Test.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test4() throws Exception {
    TestScheduler sch = new TestScheduler();

    Subject<Long> subject = PublishSubject.create();
    Observable<Long> initialObservable = subject.share()
    .map(value -> {
        System.out.println("Received value " + value);
        //new Exception().printStackTrace(System.out);
        return value;
    });

    Observable<Long> timeoutObservable = initialObservable.map(value -> {
       System.out.println("Timeout received value " + value);
       return value;
    });

    TestObserver<Long> subscriber = new TestObserver<>();
    initialObservable
    .doOnDispose(() -> { 
        System.out.println("Unsubscribed"); 
        new Exception().printStackTrace(System.out);
    })
    .timeout(1, TimeUnit.SECONDS, sch, timeoutObservable).subscribe(subscriber);
    subject.onNext(5L);
    sch.advanceTimeBy(2, TimeUnit.SECONDS);
    subject.onNext(10L);
    subject.onComplete();

    subscriber.awaitTerminalEvent();
    subscriber.assertNoErrors();
    subscriber.assertValues(5L, 10L);
}
 
Example #27
Source File: ProcessorTest.java    From state-machine with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelSignal() {
    // special scheduler that we will use to schedule signals
    TestScheduler signalScheduler = new TestScheduler();

    Processor<String> processor = createProcessor(signalScheduler);

    // do some tests with the processor
    TestSubscriber<EntityStateMachine<?, String>> ts = TestSubscriber.create();
    processor.flowable().doOnNext(m -> System.out.println(m.state())).subscribe(ts);

    ClassId<Microwave, String> microwave = ClassId.create(Microwave.class, "1");

    // button is pressed
    processor.signal(microwave, new ButtonPressed());
    ts.assertValueCount(1);
    assertEquals(MicrowaveStateMachine.State.COOKING, ts.values().get(0).state());
    // advance by less time than the timeout
    signalScheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    ts.assertValueCount(1);
    processor.cancelSignalToSelf(microwave);

    // cooking would time out by now if signal had not been cancelled
    signalScheduler.advanceTimeBy(30, TimeUnit.SECONDS);
    ts.assertValueCount(1);

    // now cancel a non-existent signal to get coverage
    processor.cancelSignalToSelf(microwave);
    ts.assertValueCount(1);

    processor.onCompleted();
    ts.assertNoErrors();
}
 
Example #28
Source File: Coincidence.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    TestScheduler sch = new TestScheduler();
    
    Flowable.interval(100, TimeUnit.MILLISECONDS, sch)
    .onBackpressureBuffer()
    .compose(coincide(Flowable.interval(300, TimeUnit.MILLISECONDS, sch), sch))
    .take(7)
    .subscribe(v -> System.out.printf("%d - %d%n", sch.now(TimeUnit.MILLISECONDS), v));
    
    sch.advanceTimeBy(1001, TimeUnit.MILLISECONDS);
}
 
Example #29
Source File: ProcessorTest.java    From state-machine with Apache License 2.0 5 votes vote down vote up
private static Processor<String> createProcessor(TestScheduler signalScheduler) {
    MicrowaveBehaviour<String> behaviour = createMicrowaveBehaviour();

    // build a processor
    Processor<String> processor = Processor //
            .behaviour(Microwave.class, behaviour) //
            .processingScheduler(Schedulers.trampoline()) //
            .signalScheduler(signalScheduler) //
            .preTransition((m, event, state) -> System.out.println("[preTransition] "
                    + event.getClass().getSimpleName() + ": " + m.state() + " -> " + state)) //
            .postTransition(m -> System.out.println("[postTransition] " + m.state())).build();
    return processor;
}
 
Example #30
Source File: BufferWithConditionAndTime.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
TestScheduler scheduler = new TestScheduler();
PublishProcessor<String> pp = PublishProcessor.create();

Function<Flowable<String>, Flowable<List<String>>> f = o -> 
        o.buffer(o.filter(v -> v.contains("Start")), 
                v -> Flowable.merge(o.filter(w -> w.contains("End")), 
                        Flowable.timer(5, TimeUnit.MINUTES, scheduler))); 

pp.publish(f)
.subscribe(System.out::println);

pp.onNext("Start");
pp.onNext("A");
pp.onNext("B");
pp.onNext("End");

pp.onNext("Start");
pp.onNext("C");

scheduler.advanceTimeBy(5, TimeUnit.MINUTES);

pp.onNext("Start");
pp.onNext("D");
pp.onNext("End");
pp.onComplete();
    
}