@Test
  public void test() {
    TestSubscriber<Object> tester = new TestSubscriber<>();
    TestScheduler scheduler = Schedulers.test();

    Observable<Long> left = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler).take(6);
    Observable<Long> right = Observable.interval(200, TimeUnit.MILLISECONDS, scheduler).take(3);

    left.groupJoin(
            right,
            i -> Observable.never(),
            i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler),
            (l, rs) -> rs.toList().map(rl -> Tuple.create(l, rl)))
        .flatMap(i -> i)
        .subscribe(tester);

    scheduler.advanceTimeTo(600, TimeUnit.MILLISECONDS);
    tester.assertReceivedOnNext(
        Arrays.asList(
            Tuple.create(0L, Arrays.asList(0L, 1L, 2L)),
            Tuple.create(1L, Arrays.asList(0L, 1L, 2L)),
            Tuple.create(2L, Arrays.asList(1L, 2L)),
            Tuple.create(3L, Arrays.asList(1L, 2L)),
            Tuple.create(4L, Arrays.asList(2L)),
            Tuple.create(5L, Arrays.asList(2L))));
  }
  @Test
  public void exampleEquivalence() {
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<Object> testerJoin = new TestSubscriber<>();
    TestSubscriber<Object> testerGroupJoin = new TestSubscriber<>();

    Observable<Long> left = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler);
    Observable<Long> right = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler);

    left.join(
            right,
            i -> Observable.timer(150, TimeUnit.MILLISECONDS, scheduler),
            i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler),
            (l, r) -> Tuple.create(l, r))
        .take(10)
        .subscribe(testerJoin);

    left.groupJoin(
            right,
            i -> Observable.timer(150, TimeUnit.MILLISECONDS, scheduler),
            i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler),
            (l, rs) -> rs.map(r -> Tuple.create(l, r)))
        .flatMap(i -> i)
        .take(10)
        .subscribe(testerGroupJoin);

    scheduler.advanceTimeTo(600, TimeUnit.MILLISECONDS);
    testerJoin.assertReceivedOnNext(testerGroupJoin.getOnNextEvents());
  }
  private void loadList(List<AppInfo> apps) {
    mRecyclerView.setVisibility(View.VISIBLE);

    Observable<AppInfo> observableApp = Observable.from(apps);

    Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS);

    Observable.zip(observableApp, tictoc, this::updateTitle)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Observer<AppInfo>() {
              @Override
              public void onCompleted() {
                Toast.makeText(getActivity(), "Here is the list!", Toast.LENGTH_LONG).show();
              }

              @Override
              public void onError(Throwable e) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
              }

              @Override
              public void onNext(AppInfo appInfo) {
                if (mSwipeRefreshLayout.isRefreshing()) {
                  mSwipeRefreshLayout.setRefreshing(false);
                }
                mAddedApps.add(appInfo);
                int position = mAddedApps.size() - 1;
                mAdapter.addApplication(position, appInfo);
                mRecyclerView.smoothScrollToPosition(position);
              }
            });
  }
  @Test
  public void test() {
    TestSubscriber<Long> tester = new TestSubscriber<>();
    TestScheduler scheduler = Schedulers.test();

    Observable.switchOnNext(
            Observable.interval(100, TimeUnit.MILLISECONDS, scheduler)
                .map(i -> Observable.interval(30, TimeUnit.MILLISECONDS, scheduler).map(i2 -> i)))
        .distinctUntilChanged()
        .subscribe(tester);

    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    tester.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L));
    tester.assertNoErrors();
    assertEquals(tester.getOnCompletedEvents().size(), 0);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.progress_bar_activity);

    Observable.interval(1, TimeUnit.SECONDS)
        .take(4)
        .compose(RxProgressBar.withAny((ProgressBar) findViewById(R.id.progressBar)))
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Action1<Long>() {
              @Override
              public void call(Long aLong) {
                Toast.makeText(ProgressBarActivity.this, "Value " + aLong, Toast.LENGTH_SHORT)
                    .show();
                Log.i("tag", "emited value " + aLong);
              }
            },
            new Action1<Throwable>() {
              @Override
              public void call(Throwable throwable) {
                Log.e("tag", "error ", throwable);
              }
            });
  }
  private void loadList(List<AppInfo> apps) {
    mRecyclerView.setVisibility(View.VISIBLE);

    Observable<AppInfo> appsSequence =
        Observable.interval(1000, TimeUnit.MILLISECONDS)
            .map(
                position -> {
                  App.L.debug("Position: " + position);
                  return apps.get(position.intValue());
                });
    Observable<Long> tictoc = Observable.interval(1000, TimeUnit.MILLISECONDS);

    appsSequence
        .join(
            tictoc,
            appInfo -> Observable.timer(2, TimeUnit.SECONDS),
            time -> Observable.timer(0, TimeUnit.SECONDS),
            this::updateTitle)
        .observeOn(AndroidSchedulers.mainThread())
        .take(10)
        .subscribe(
            new Observer<AppInfo>() {
              @Override
              public void onCompleted() {
                Toast.makeText(getActivity(), "Here is the list!", Toast.LENGTH_LONG).show();
              }

              @Override
              public void onError(Throwable e) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
              }

              @Override
              public void onNext(AppInfo appInfo) {
                if (mSwipeRefreshLayout.isRefreshing()) {
                  mSwipeRefreshLayout.setRefreshing(false);
                }
                mAddedApps.add(appInfo);
                int position = mAddedApps.size() - 1;
                mAdapter.addApplication(position, appInfo);
                mRecyclerView.smoothScrollToPosition(position);
              }
            });
  }
  public void exampleTimestamp() {
    Observable<Long> values = Observable.interval(100, TimeUnit.MILLISECONDS);

    values.take(3).timestamp().subscribe(new PrintSubscriber("Timestamp"));

    // Timestamp: Timestamped(timestampMillis = 1428611094943, value = 0)
    // Timestamp: Timestamped(timestampMillis = 1428611095037, value = 1)
    // Timestamp: Timestamped(timestampMillis = 1428611095136, value = 2)
    // Timestamp: Completed
  }
  public void exampleTimeInteval() {
    Observable<Long> values = Observable.interval(100, TimeUnit.MILLISECONDS);

    values.take(3).timeInterval().subscribe(new PrintSubscriber("TimeInterval"));

    // TimeInterval: TimeInterval [intervalInMilliseconds=131, value=0]
    // TimeInterval: TimeInterval [intervalInMilliseconds=75, value=1]
    // TimeInterval: TimeInterval [intervalInMilliseconds=100, value=2]
    // TimeInterval: Completed
  }
  public void example() {
    Observable<String> left =
        Observable.interval(100, TimeUnit.MILLISECONDS).map(i -> "L" + i).take(6);
    Observable<String> right =
        Observable.interval(200, TimeUnit.MILLISECONDS).map(i -> "R" + i).take(3);

    left.groupJoin(
            right,
            i -> Observable.never(),
            i -> Observable.timer(0, TimeUnit.MILLISECONDS),
            (l, rs) -> rs.toList().subscribe(list -> System.out.println(l + ": " + list)))
        .subscribe();

    // L0: [R0, R1, R2]
    // L1: [R0, R1, R2]
    // L2: [R1, R2]
    // L3: [R1, R2]
    // L4: [R2]
    // L5: [R2]
  }
  public void exampleReplayWithBufferSize() throws InterruptedException {
    ConnectableObservable<Long> source =
        Observable.interval(1000, TimeUnit.MILLISECONDS).take(5).replay(2);

    source.connect();
    Thread.sleep(4500);
    source.subscribe(System.out::println);

    // 2
    // 3
    // 4
  }
  public void testUnSubscribeForScheduler(Scheduler scheduler) throws InterruptedException {

    final AtomicInteger countReceived = new AtomicInteger();
    final AtomicInteger countGenerated = new AtomicInteger();
    final SafeObservableSubscription s = new SafeObservableSubscription();
    final CountDownLatch latch = new CountDownLatch(1);

    s.wrap(
        Observable.interval(50, TimeUnit.MILLISECONDS)
            .map(
                new Func1<Long, Long>() {
                  @Override
                  public Long call(Long aLong) {
                    System.out.println("generated " + aLong);
                    countGenerated.incrementAndGet();
                    return aLong;
                  }
                })
            .subscribeOn(scheduler)
            .observeOn(scheduler)
            .subscribe(
                new Observer<Long>() {
                  @Override
                  public void onCompleted() {
                    System.out.println("--- completed");
                  }

                  @Override
                  public void onError(Throwable e) {
                    System.out.println("--- onError");
                  }

                  @Override
                  public void onNext(Long args) {
                    if (countReceived.incrementAndGet() == 2) {
                      s.unsubscribe();
                      latch.countDown();
                    }
                    System.out.println("==> Received " + args);
                  }
                }));

    latch.await(1000, TimeUnit.MILLISECONDS);

    System.out.println("----------- it thinks it is finished ------------------ ");
    Thread.sleep(100);

    assertEquals(2, countGenerated.get());
  }
Beispiel #12
0
  public static void main(String[] args) throws InterruptedException {

    Function<String, Subscriber> logSubFunc =
        (prefix) -> {
          return Subscribers.create(
              e -> logger.printf(Level.INFO, "%s : %s", prefix, e),
              e -> logger.error(prefix, e),
              () -> logger.info(prefix + " Completed."));
        };

    Observable.interval(100L, TimeUnit.MILLISECONDS, Schedulers.immediate())
        .take(5)
        .doOnEach(debug("100 ms"))
        .subscribe();

    Thread.sleep(1000);
    Observable<Integer> simpleRetry =
        Observable.create(new ErrorEmitter()).doOnEach(debug("simple retry")).retry(3);

    simpleRetry.subscribe(
        // logSubFunc.apply("simple retry")
        );

    //
    //        Func1<? super Observable<? extends java.lang.Throwable>, Observable> emitError =
    // (errorObs) -> {
    //            return errorObs.flatMap(error -> Observable.error(error));
    //        };
    //
    //        Observable<Integer> dummyWhen = Observable.create(new ErrorEmitter())
    //                .retryWhen(errorEvent -> emitError.call(errorEvent))
    //                .retry((attempts, error) -> {
    //                    logger.printf(Level.ERROR, "%d retry due to %s.", attempts,
    // error.getMessage());
    //                    return attempts < 3;
    //                });
    //        dummyWhen.subscribe(logSubFunc.apply("emit error retry"));
    //
    //        Func1<? super Observable<? extends java.lang.Throwable>, ? extends Observable<?>>
    //                delayOneSec = errorObs -> errorObs.flatMap(error ->
    //                Observable.timer(1L, TimeUnit.SECONDS)
    //        );
    //
    //        Observable<Integer> oneSecDelayThenRetry = Observable.create(new ErrorEmitter())
    //                .retryWhen(errorEvent -> delayOneSec.call(errorEvent));
    //        oneSecDelayThenRetry.subscribe(logSubFunc.apply("one sec delay"));

    Thread.sleep(10 * 1000);
  }
 @OnClick(R.id.test_btn)
 public void onClick() {
   Toast.makeText(CustomViewActivity.this, "click!", Toast.LENGTH_SHORT).show();
   Observable.interval(1000, TimeUnit.MILLISECONDS)
       .subscribeOn(AndroidSchedulers.mainThread())
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(
           new Action1<Long>() {
             @Override
             public void call(Long aLong) {
               mTestBtn.setAngleRange(mTestBtn.getAngleRange() + 20);
               Log.i("plus", "=======================");
             }
           });
 }
  private void startCountDown() {

    /* final CountDownLatch latch = new CountDownLatch(5);
    latch.countDown();

    Observable
        .interval(1, TimeUnit.SECONDS)
        .take(5)
        .toBlocking()
        .forEach(new Action1<Long>() {
          @Override public void call(Long counter) {
            System.out.println("Got: " + counter);
          }
        });*/

    Observable.interval(0, 1, TimeUnit.SECONDS)
        .take(10)
        .map(
            new Func1<Long, Long>() {
              @Override
              public Long call(Long aLong) {
                return 9 - aLong;
              }
            })
        .doOnSubscribe(
            new Action0() {
              @Override
              public void call() {
                codeBtn.setEnabled(false);
              }
            })
        .compose(SchedulersCompat.<Long>applyComputationSchedulers())
        .compose(RegisterActivity.this.<Long>bindUntilEvent(ActivityEvent.DESTROY))
        .subscribe(
            new SimpleObserver<Long>() {
              @Override
              public void onCompleted() {
                /*60秒倒计时结束,回复按钮状态*/
                codeBtn.setEnabled(true);
                codeBtn.setText("点击获取");
              }

              @Override
              public void onNext(Long aLong) {
                codeBtn.setText(aLong + "");
              }
            });
  }
  @Test
  public void testReplayWithBufferSize() {
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<Long> tester = new TestSubscriber<>();

    ConnectableObservable<Long> source =
        Observable.interval(1000, TimeUnit.MILLISECONDS, scheduler).take(5).replay(2, scheduler);

    source.connect();
    scheduler.advanceTimeBy(4500, TimeUnit.MILLISECONDS);
    source.subscribe(tester);
    scheduler.triggerActions();
    tester.assertReceivedOnNext(Arrays.asList(2L, 3L));
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    tester.assertReceivedOnNext(Arrays.asList(2L, 3L, 4L));
  }
Beispiel #16
0
  private void onStart() {
    Subscription subscription =
        Observable.interval(20, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .filter(
                new Func1<Long, Boolean>() {
                  @Override
                  public Boolean call(Long aLong) {
                    mFrontMoveLength += FRONT_SPEED;
                    mBackMoveLength += BACK_SPEED;

                    for (int i = 0, size = mFrontPointsList.size(); i < size; i++) {
                      mFrontPointsList.get(i).x += FRONT_SPEED;
                      mBackPointsList.get(i).x += BACK_SPEED;
                    }

                    if (mFrontMoveLength >= mWaveWidth) {
                      // 波浪右移超过一个完整波浪后复位
                      mFrontMoveLength = 0;
                      resetFrontPoints();
                    }
                    if (mBackMoveLength >= mWaveWidth) {
                      // 波浪右移超过一个完整波浪后复位
                      mBackMoveLength = 0;
                      resetBackPoints();
                    }
                    return true;
                  }
                })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new Action1<Long>() {
                  @Override
                  public void call(Long aLong) {
                    invalidate();
                  }
                },
                new Action1<Throwable>() {
                  @Override
                  public void call(Throwable throwable) {
                    throwable.toString();
                  }
                });
    mCompositeSubscription = new CompositeSubscription();
    mCompositeSubscription.add(subscription);
  }
  @Test
  public void testTimestamp() {
    TestSubscriber<Timestamped<Long>> tester = new TestSubscriber<>();
    TestScheduler scheduler = Schedulers.test();

    Observable<Long> values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler);

    values.take(3).timestamp(scheduler).subscribe(tester);

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);

    assertEquals(tester.getOnNextEvents().get(0).getTimestampMillis(), 100);
    assertEquals(tester.getOnNextEvents().get(1).getTimestampMillis(), 200);
    assertEquals(tester.getOnNextEvents().get(2).getTimestampMillis(), 300);
    tester.assertTerminalEvent();
    tester.assertNoErrors();
  }
  @Test
  public void testMultipleObservers() {
    Observer<Object> o1 = mock(Observer.class);
    Observer<Object> o2 = mock(Observer.class);

    TestScheduler s = new TestScheduler();

    Observable<Long> timer = Observable.interval(500, TimeUnit.MILLISECONDS, s).take(2);
    Observable<Long> o = Observable.concat(timer, timer);

    o.subscribe(o1);
    o.subscribe(o2);

    InOrder inOrder1 = inOrder(o1);
    InOrder inOrder2 = inOrder(o2);

    s.advanceTimeBy(500, TimeUnit.MILLISECONDS);

    inOrder1.verify(o1, times(1)).onNext(0L);
    inOrder2.verify(o2, times(1)).onNext(0L);

    s.advanceTimeBy(500, TimeUnit.MILLISECONDS);

    inOrder1.verify(o1, times(1)).onNext(1L);
    inOrder2.verify(o2, times(1)).onNext(1L);

    s.advanceTimeBy(500, TimeUnit.MILLISECONDS);

    inOrder1.verify(o1, times(1)).onNext(0L);
    inOrder2.verify(o2, times(1)).onNext(0L);

    s.advanceTimeBy(500, TimeUnit.MILLISECONDS);

    inOrder1.verify(o1, times(1)).onNext(1L);
    inOrder2.verify(o2, times(1)).onNext(1L);

    inOrder1.verify(o1, times(1)).onCompleted();
    inOrder2.verify(o2, times(1)).onCompleted();

    verify(o1, never()).onError(any(Throwable.class));
    verify(o2, never()).onError(any(Throwable.class));
  }
Beispiel #19
0
  /** 进入APP倒计时 使用RxJava进行异步处理 每秒调用一次enterMain */
  public void startTiming() {

    // 订阅事件,每秒判断一次是否进入APP,并刷新UI展示
    Subscription subscription =
        Observable.interval(TIME_SECOND, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new Action1<Long>() {
                  @Override
                  public void call(Long aLong) {
                    // aLong代表interval调用次数
                    enterApp(aLong);
                    Log.d("test leak", aLong + "");
                  }
                });

    // 将 订阅事件 加入 subscription集合(Set),用于与Activity生命周期绑定,onDestroy时解除事件注册
    compositeSubscription.add(subscription);
  }
  @Test
  public void testReplayWithTime() throws InterruptedException {
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<Long> tester = new TestSubscriber<>();

    ConnectableObservable<Long> source =
        Observable.interval(1000, TimeUnit.MILLISECONDS, scheduler)
            .take(5)
            .replay(2000, TimeUnit.MILLISECONDS, scheduler);

    source.connect();
    scheduler.advanceTimeBy(4500, TimeUnit.MILLISECONDS);
    source.subscribe(tester);
    tester.assertReceivedOnNext(Arrays.asList(2L, 3L));
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    tester.assertReceivedOnNext(Arrays.asList(2L, 3L, 4L));

    //		2
    //		3
    //		4
  }
 private void autoLoop() {
   if (subscribe_auto == null || subscribe_auto.isUnsubscribed()) {
     subscribe_auto =
         Observable.interval(3000, 3000, TimeUnit.MILLISECONDS)
             // 延时3000 ,每间隔3000,时间单位
             .compose(this.<Long>bindToLifecycle())
             .observeOn(AndroidSchedulers.mainThread())
             .subscribe(
                 new Action1<Long>() {
                   @Override
                   public void call(Long aLong) {
                     int currentIndex = mViewPager.getCurrentItem();
                     if (++currentIndex == loopAdapter.getCount()) {
                       mViewPager.setCurrentItem(0);
                     } else {
                       mViewPager.setCurrentItem(currentIndex, true);
                     }
                   }
                 });
   }
 }
  public void exampleReplay() throws InterruptedException {
    ConnectableObservable<Long> cold = Observable.interval(200, TimeUnit.MILLISECONDS).replay();
    cold.connect();

    System.out.println("Subscribe first");
    cold.subscribe(i -> System.out.println("First: " + i));
    Thread.sleep(700);
    System.out.println("Subscribe second");
    cold.subscribe(i -> System.out.println("Second: " + i));
    Thread.sleep(500);

    // Subscribe first
    // First: 0
    // First: 1
    // First: 2
    // Subscribe second
    // Second: 0
    // Second: 1
    // Second: 2
    // First: 3
    // Second: 3
  }
  @Test
  public void testReplay() throws InterruptedException {
    TestScheduler scheduler = Schedulers.test();
    TestSubscriber<Long> tester1 = new TestSubscriber<>();
    TestSubscriber<Long> tester2 = new TestSubscriber<>();

    ConnectableObservable<Long> cold =
        Observable.interval(200, TimeUnit.MILLISECONDS, scheduler).replay();
    Subscription connection = cold.connect();

    cold.subscribe(tester1);
    scheduler.advanceTimeBy(700, TimeUnit.MILLISECONDS);
    tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L));
    tester2.assertReceivedOnNext(Arrays.asList());

    cold.subscribe(tester2);
    tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L));
    tester2.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L));
    scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
    tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L, 5L));
    tester2.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L, 5L));

    connection.unsubscribe();
  }
 public <T> Observable<T> executedEach(long millis, Observable<T> observable) {
   return Observable.interval(0, millis, TimeUnit.MILLISECONDS, executionScheduler)
       .doOnNext(i -> logger.debug(this, "Interval: " + i))
       .doOnUnsubscribe(() -> logger.debug(this, "Interval stopped"))
       .flatMap(i -> observable);
 }