Observable.Generate in RxJava?

时间:2016-06-07 15:44:51

标签: rx-java corecursion

.NET Reactive Extensions有一个使用corecursion生成序列的简洁方法,称为Observable.Generate

RxJava中是否有类比方法允许通过corecursion生成数据?如果没有,是否可以基于现有方法实施?

1 个答案:

答案 0 :(得分:2)

这不是完全匹配,但我们有SyncOnSubscribe(和AsyncOnSubscriber)可以生成值,例如:

@Test
public void testRange() {
    final int start = 1;
    final int count = 4000;
    OnSubscribe<Integer> os = SyncOnSubscribe.createStateful(new Func0<Integer>(){
        @Override
        public Integer call() {
            return start;
        }}, 
        new Func2<Integer, Observer<? super Integer>, Integer>() {
            @Override
            public Integer call(Integer state, Observer<? super Integer> subscriber) {
                subscriber.onNext(state);
                if (state == count) {
                    subscriber.onCompleted();
                }
                return state + 1;
            }
        });

    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);
    InOrder inOrder = inOrder(o);

    Observable.create(os).subscribe(o);

    verify(o, never()).onError(any(TestException.class));
    inOrder.verify(o, times(count)).onNext(any(Integer.class));
    inOrder.verify(o).onCompleted();
    inOrder.verifyNoMoreInteractions();
}