OperationTakeWhile { public static <T> OnSubscribeFunc<T> takeWhileWithIndex(final Observable<? extends T> items, final Func2<? super T, ? super Integer, Boolean> predicate) { return new OnSubscribeFunc<T>() { @Override public Subscription onSubscribe(Observer<? super T> observer) { return new TakeWhile<T>(items, predicate).onSubscribe(observer); } }; }  static OnSubscribeFunc<T> takeWhile(final Observable<? extends T> items, final Func1<? super T, Boolean> predicate); static OnSubscribeFunc<T> takeWhileWithIndex(final Observable<? extends T> items, final Func2<? super T, ? super Integer, Boolean> predicate);  }
@Test public void testTakeWhile2() { Observable<String> w = Observable.from("one", "two", "three"); Observable<String> take = Observable.create(takeWhileWithIndex(w, new Func2<String, Integer, Boolean>() { @Override public Boolean call(String input, Integer index) { return index < 2; } })); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); take.subscribe(observer); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onNext("two"); verify(observer, never()).onNext("three"); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); }
@Test public void testUnsubscribeAfterTake() { Subscription s = mock(Subscription.class); TestObservable w = new TestObservable(s, "one", "two", "three"); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); Observable<String> take = Observable.create(takeWhileWithIndex(Observable.create(w), new Func2<String, Integer, Boolean>() { @Override public Boolean call(String s, Integer index) { return index < 1; } })); take.subscribe(observer); try { w.t.join(); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } System.out.println("TestObservable thread finished"); verify(observer, times(1)).onNext("one"); verify(observer, never()).onNext("two"); verify(observer, never()).onNext("three"); verify(s, times(1)).unsubscribe(); }