Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

rx java - How to use TestScheduler in RxJava

How should I use RxJava's TestScheduler? I come from a .NET background but the TestScheduler in RxJava does not seem to work the same way as the test scheduler in .NET rx.

Here is sample code that I want to test

Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS);
contactsRepository.find(index)
  .buffer(MAX_CONTACTS_FETCH)
  .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() {
    @Override
    public List<ContactDto> call(List<ContactDto> contactList, Long aLong) {
      return contactList;
    }
  }).subscribe()

I've tried:

subscribeOn(testScheduler)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS);
testScheduler.triggerActions();

with no luck.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I made a little example of how to use a TestScheduler. I think it's very similar to the .NET implementation

@Test
public void should_test_the_test_schedulers() {
    TestScheduler scheduler = new TestScheduler();
    final List<Long> result = new ArrayList<>();
    Observable.interval(1, TimeUnit.SECONDS, scheduler)
        .take(5)
        .subscribe(result::add);
    assertTrue(result.isEmpty());
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    assertEquals(2, result.size());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    assertEquals(5, result.size());
}

https://github.com/bric3/demo-rxjava-humantalk/blob/master/src/test/java/demo/humantalk/rxjava/SchedulersTest.java

EDIT According to your code : you should pass the scheduler to the Observable.interval operation, as this is what you want to control :

    TestScheduler scheduler = new TestScheduler();

    Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
    Subscription toBeTested = Observable.from(Arrays.asList(1, 2, 3, 4, 5))
            .buffer(3)
            .zipWith(tick, (i, t) -> i)
            .subscribe(System.out::println);

    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...