本文介绍了如何在 RxJava 中使用 TestScheduler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该如何使用 RxJava 的 TestScheduler
?我来自 .NET 背景,但 RxJava 中的 TestScheduler
似乎与 .NET rx 中的测试调度程序的工作方式不同.
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()
我试过了:
subscribeOn(testScheduler)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS);
testScheduler.triggerActions();
运气不好.
推荐答案
我做了一个关于如何使用 TestScheduler
的小例子.我认为它与 .NET 实现非常相似
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());
}
编辑根据您的代码:您应该将调度程序传递给 Observable.interval
操作,因为这是您想要控制的:
EDITAccording 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);
这篇关于如何在 RxJava 中使用 TestScheduler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!