Example #1
0
  @Test
  public void testSwitchWhenOuterCompleteBeforeInner() {
    Observable<Observable<String>> source =
        Observable.create(
            new Observable.OnSubscribeFunc<Observable<String>>() {
              @Override
              public Subscription onSubscribe(Observer<? super Observable<String>> observer) {
                publishNext(
                    observer,
                    50,
                    Observable.create(
                        new Observable.OnSubscribeFunc<String>() {
                          @Override
                          public Subscription onSubscribe(Observer<? super String> observer) {
                            publishNext(observer, 70, "one");
                            publishNext(observer, 100, "two");
                            publishCompleted(observer, 200);
                            return Subscriptions.empty();
                          }
                        }));
                publishCompleted(observer, 60);

                return Subscriptions.empty();
              }
            });

    Observable<String> sampled = Observable.create(OperationSwitch.switchDo(source));
    sampled.subscribe(observer);

    InOrder inOrder = inOrder(observer);

    scheduler.advanceTimeTo(350, TimeUnit.MILLISECONDS);
    inOrder.verify(observer, times(2)).onNext(anyString());
    inOrder.verify(observer, times(1)).onCompleted();
  }
Example #2
0
    @Test
    public void testTakeZeroDoesntLeakError() {
      final AtomicBoolean subscribed = new AtomicBoolean(false);
      final AtomicBoolean unSubscribed = new AtomicBoolean(false);
      Observable<String> source =
          Observable.create(
              new Func1<Observer<String>, Subscription>() {
                @Override
                public Subscription call(Observer<String> observer) {
                  subscribed.set(true);
                  observer.onError(new Throwable("test failed"));
                  return new Subscription() {
                    @Override
                    public void unsubscribe() {
                      unSubscribed.set(true);
                    }
                  };
                }
              });

      @SuppressWarnings("unchecked")
      Observer<String> aObserver = mock(Observer.class);

      Observable.create(take(source, 0)).subscribe(aObserver);
      assertTrue("source subscribed", subscribed.get());
      assertTrue("source unsubscribed", unSubscribed.get());

      verify(aObserver, never()).onNext(anyString());
      // even though onError is called we take(0) so shouldn't see it
      verify(aObserver, never()).onError(any(Throwable.class));
      verify(aObserver, times(1)).onCompleted();
      verifyNoMoreInteractions(aObserver);
    }
  /** Simple concat of 2 asynchronous observables ensuring it emits in correct order. */
  @SuppressWarnings("unchecked")
  @Test
  public void testSimpleAsyncConcat() {
    Observer<String> observer = mock(Observer.class);

    TestObservable<String> o1 = new TestObservable<String>("one", "two", "three");
    TestObservable<String> o2 = new TestObservable<String>("four", "five", "six");

    Observable.concat(Observable.create(o1), Observable.create(o2)).subscribe(observer);

    try {
      // wait for async observables to complete
      o1.t.join();
      o2.t.join();
    } catch (Throwable e) {
      throw new RuntimeException("failed waiting on threads");
    }

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer, times(1)).onNext("one");
    inOrder.verify(observer, times(1)).onNext("two");
    inOrder.verify(observer, times(1)).onNext("three");
    inOrder.verify(observer, times(1)).onNext("four");
    inOrder.verify(observer, times(1)).onNext("five");
    inOrder.verify(observer, times(1)).onNext("six");
  }
Example #4
0
    @Test
    public void testMergeObservableOfObservables() {
      final Observable<String> o1 = new TestSynchronousObservable();
      final Observable<String> o2 = new TestSynchronousObservable();

      Observable<Observable<String>> observableOfObservables =
          Observable.create(
              new Func1<Observer<Observable<String>>, Subscription>() {

                @Override
                public Subscription call(Observer<Observable<String>> observer) {
                  // simulate what would happen in an observable
                  observer.onNext(o1);
                  observer.onNext(o2);
                  observer.onCompleted();

                  return new Subscription() {

                    @Override
                    public void unsubscribe() {
                      // unregister ... will never be called here since we are executing
                      // synchronously
                    }
                  };
                }
              });
      Observable<String> m = Observable.create(merge(observableOfObservables));
      m.subscribe(stringObserver);

      verify(stringObserver, never()).onError(any(Exception.class));
      verify(stringObserver, times(1)).onCompleted();
      verify(stringObserver, times(2)).onNext("hello");
    }
  /** If the 'other' onCompletes then we unsubscribe from the source and onComplete */
  @Test
  @SuppressWarnings("unchecked")
  public void testTakeUntilOtherCompleted() {
    Subscription sSource = mock(Subscription.class);
    Subscription sOther = mock(Subscription.class);
    TestObservable source = new TestObservable(sSource);
    TestObservable other = new TestObservable(sOther);

    Observer<String> result = mock(Observer.class);
    Observable<String> stringObservable =
        Observable.create(source).takeUntil(Observable.create(other));
    stringObservable.subscribe(result);
    source.sendOnNext("one");
    source.sendOnNext("two");
    other.sendOnCompleted();
    source.sendOnNext("three");

    verify(result, times(1)).onNext("one");
    verify(result, times(1)).onNext("two");
    verify(result, times(0)).onNext("three");
    verify(result, times(1)).onCompleted();
    verify(sSource, times(1)).unsubscribe();
    verify(sOther, times(1))
        .unsubscribe(); // unsubscribed since SafeSubscriber unsubscribes after onComplete
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testTakeUntilSourceError() {
    Subscription sSource = mock(Subscription.class);
    Subscription sOther = mock(Subscription.class);
    TestObservable source = new TestObservable(sSource);
    TestObservable other = new TestObservable(sOther);
    Throwable error = new Throwable();

    Observer<String> result = mock(Observer.class);
    Observable<String> stringObservable =
        Observable.create(source).takeUntil(Observable.create(other));
    stringObservable.subscribe(result);
    source.sendOnNext("one");
    source.sendOnNext("two");
    source.sendOnError(error);
    source.sendOnNext("three");

    verify(result, times(1)).onNext("one");
    verify(result, times(1)).onNext("two");
    verify(result, times(0)).onNext("three");
    verify(result, times(1)).onError(error);
    verify(sSource, times(1)).unsubscribe();
    verify(sOther, times(1)).unsubscribe();
  }
Example #7
0
    @Test
    public void testDebounceNeverEmits() {
      Observable<String> source =
          Observable.create(
              new OnSubscribeFunc<String>() {
                @Override
                public Subscription onSubscribe(Observer<? super String> observer) {
                  // all should be skipped since they are happening faster than the 200ms timeout
                  publishNext(observer, 100, "a"); // Should be skipped
                  publishNext(observer, 200, "b"); // Should be skipped
                  publishNext(observer, 300, "c"); // Should be skipped
                  publishNext(observer, 400, "d"); // Should be skipped
                  publishNext(observer, 500, "e"); // Should be skipped
                  publishNext(observer, 600, "f"); // Should be skipped
                  publishNext(observer, 700, "g"); // Should be skipped
                  publishNext(observer, 800, "h"); // Should be skipped
                  publishCompleted(
                      observer, 900); // Should be published as soon as the timeout expires.

                  return Subscriptions.empty();
                }
              });

      Observable<String> sampled =
          Observable.create(
              OperationDebounce.debounce(source, 200, TimeUnit.MILLISECONDS, scheduler));
      sampled.subscribe(observer);

      scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS);
      InOrder inOrder = inOrder(observer);
      inOrder.verify(observer, times(0)).onNext(anyString());
      scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS);
      inOrder.verify(observer, times(1)).onCompleted();
      inOrder.verifyNoMoreInteractions();
    }
  @Test
  public void testResumeNext() {
    Subscription s = mock(Subscription.class);
    // Trigger failure on second element
    TestObservable f = new TestObservable(s, "one", "fail", "two", "three");
    Observable<String> w = Observable.create(f);
    Observable<String> resume = Observable.from("twoResume", "threeResume");
    Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume));

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);
    observable.subscribe(observer);

    try {
      f.t.join();
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }

    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onCompleted();
    verify(observer, times(1)).onNext("one");
    verify(observer, Mockito.never()).onNext("two");
    verify(observer, Mockito.never()).onNext("three");
    verify(observer, times(1)).onNext("twoResume");
    verify(observer, times(1)).onNext("threeResume");
  }
  @Test
  public void testConcatConcurrentWithInfinity() {
    final TestObservable<String> w1 = new TestObservable<String>("one", "two", "three");
    // This observable will send "hello" MAX_VALUE time.
    final TestObservable<String> w2 = new TestObservable<String>("hello", Integer.MAX_VALUE);

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);
    @SuppressWarnings("unchecked")
    TestObservable<Observable<String>> observableOfObservables =
        new TestObservable<Observable<String>>(Observable.create(w1), Observable.create(w2));
    Observable<String> concatF = Observable.concat(Observable.create(observableOfObservables));

    concatF.take(50).subscribe(observer);

    // Wait for the thread to start up.
    try {
      w1.waitForThreadDone();
      w2.waitForThreadDone();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer, times(1)).onNext("one");
    inOrder.verify(observer, times(1)).onNext("two");
    inOrder.verify(observer, times(1)).onNext("three");
    inOrder.verify(observer, times(47)).onNext("hello");
    verify(observer, times(1)).onCompleted();
    verify(observer, never()).onError(any(Throwable.class));
  }
Example #10
0
  @Test
  public void testSwitchIssue737() {
    // https://github.com/Netflix/RxJava/issues/737
    Observable<Observable<String>> source =
        Observable.create(
            new Observable.OnSubscribeFunc<Observable<String>>() {
              @Override
              public Subscription onSubscribe(Observer<? super Observable<String>> observer) {
                publishNext(
                    observer,
                    0,
                    Observable.create(
                        new Observable.OnSubscribeFunc<String>() {
                          @Override
                          public Subscription onSubscribe(Observer<? super String> observer) {
                            publishNext(observer, 10, "1-one");
                            publishNext(observer, 20, "1-two");
                            // The following events will be ignored
                            publishNext(observer, 30, "1-three");
                            publishCompleted(observer, 40);
                            return Subscriptions.empty();
                          }
                        }));
                publishNext(
                    observer,
                    25,
                    Observable.create(
                        new Observable.OnSubscribeFunc<String>() {
                          @Override
                          public Subscription onSubscribe(Observer<? super String> observer) {
                            publishNext(observer, 10, "2-one");
                            publishNext(observer, 20, "2-two");
                            publishNext(observer, 30, "2-three");
                            publishCompleted(observer, 40);
                            return Subscriptions.empty();
                          }
                        }));
                publishCompleted(observer, 30);
                return Subscriptions.empty();
              }
            });

    Observable<String> sampled = Observable.create(OperationSwitch.switchDo(source));
    sampled.subscribe(observer);

    scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS);

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer, times(1)).onNext("1-one");
    inOrder.verify(observer, times(1)).onNext("1-two");
    inOrder.verify(observer, times(1)).onNext("2-one");
    inOrder.verify(observer, times(1)).onNext("2-two");
    inOrder.verify(observer, times(1)).onNext("2-three");
    inOrder.verify(observer, times(1)).onCompleted();
    inOrder.verifyNoMoreInteractions();
  }
  private void onFavoriteItemSelected(boolean favorited) {
    Observable<Boolean> obsAction;

    if (favorited) {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.addToFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(true).build();
                  subscriber.onNext(true);
                } catch (Exception e) {
                  Timber.w(e, "Unable to add FeedItem to favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (result) {
                  Toast.makeText(getActivity(), R.string.added_to_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    } else {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.removeFromFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(false).build();
                  subscriber.onNext(false);
                } catch (Exception e) {
                  Timber.w(e, "Unable to remove FeedItem from favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (!result) {
                  Toast.makeText(getActivity(), R.string.removed_from_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    }
  }
Example #12
0
  @Test
  public void shouldNotCallOnSubscribeWhenSubscriptionUnsubscribedBeforeDelay() {
    Observable.OnSubscribe<Integer> onSubscribe = mock(Observable.OnSubscribe.class);
    Handler handler = spy(new Handler());

    final Worker worker = spy(new HandlerScheduler.HandlerWorker(handler));
    Scheduler scheduler =
        new Scheduler() {
          @Override
          public Worker createWorker() {
            return worker;
          }
        };

    Subscription subscription =
        Observable.create(onSubscribe).delaySubscription(1, MINUTES, scheduler).subscribe();

    verify(worker).schedule(any(Action0.class), eq(1L), eq(MINUTES));
    verify(handler).postDelayed(any(Runnable.class), eq(MINUTES.toMillis(1)));

    subscription.unsubscribe();

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    verify(onSubscribe, never()).call(any(Subscriber.class));
    verify(handler).removeCallbacks(any(Runnable.class));
  }
 /** Bind view on immediate scheduler. */
 public static <T> Observable<T> bindViewImmediate(View view, Observable<T> source) {
   if (view == null || source == null)
     throw new IllegalArgumentException("View and Observable must be given");
   return source
       .takeUntil(Observable.create(new OnSubscribeViewDetachedFromWindowFirst(view)))
       .observeOn(Schedulers.immediate());
 }
  /**
   * Observes WiFi Access Points. Returns fresh list of Access Points whenever WiFi signal strength
   * changes.
   *
   * @param context Context of the activity or an application
   * @return RxJava Observable with list of WiFi scan results
   */
  public Observable<List<ScanResult>> observeWifiAccessPoints(final Context context) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.startScan(); // without starting scan, we may never receive any scan results

    final IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    return Observable.create(
        new Observable.OnSubscribe<List<ScanResult>>() {
          @Override
          public void call(final Subscriber<? super List<ScanResult>> subscriber) {
            final BroadcastReceiver receiver =
                new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context context, Intent intent) {
                    wifiManager
                        .startScan(); // we need to start scan again to get fresh results ASAP
                    subscriber.onNext(wifiManager.getScanResults());
                  }
                };

            context.registerReceiver(receiver, filter);

            subscriber.add(
                unsubscribeInUiThread(
                    new Action0() {
                      @Override
                      public void call() {
                        context.unregisterReceiver(receiver);
                      }
                    }));
          }
        });
  }
  /**
   * Observes WiFi signal level. Returns WiFi signal level as an integer
   *
   * @param context Context of the activity or an application
   * @param numLevels The number of levels to consider in the calculated level as Integer
   * @return RxJava Observable with WiFi signal level
   */
  public Observable<Integer> observeWifiSignalLevel(final Context context, final int numLevels) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    final IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.RSSI_CHANGED_ACTION);

    return Observable.create(
            new Observable.OnSubscribe<Integer>() {
              @Override
              public void call(final Subscriber<? super Integer> subscriber) {
                final BroadcastReceiver receiver =
                    new BroadcastReceiver() {
                      @Override
                      public void onReceive(Context context, Intent intent) {
                        final int rssi = wifiManager.getConnectionInfo().getRssi();
                        final int level = WifiManager.calculateSignalLevel(rssi, numLevels);
                        subscriber.onNext(level);
                      }
                    };

                context.registerReceiver(receiver, filter);

                subscriber.add(
                    unsubscribeInUiThread(
                        new Action0() {
                          @Override
                          public void call() {
                            context.unregisterReceiver(receiver);
                          }
                        }));
              }
            })
        .defaultIfEmpty(0);
  }
Example #16
0
  public Subscription subscribeData(Observer<List<GankBeauty>> observer) {
    if (mCache == null) {
      mCache = BehaviorSubject.create();
      Observable.create(
              new Observable.OnSubscribe<List<GankBeauty>>() {

                @Override
                public void call(Subscriber<? super List<GankBeauty>> subscriber) {
                  List<GankBeauty> itemList = getDataFromDisk(DATA_FILE_NAME);
                  if (ListUtils.isEmpty(itemList)) {
                    Logger.d("Load data from network");
                    setDataSource(DATA_SOURCE_NETWORK);
                    loadFromNetwork();
                  } else {
                    Logger.d("Load data from disk");
                    setDataSource(DATA_SOURCE_DISK);
                    subscriber.onNext(itemList);
                  }
                }
              })
          .subscribeOn(Schedulers.io())
          .subscribe(mCache);
    } else {
      Logger.d("Load data from memory.");
      setDataSource(DATA_SOURCE_MEMORY);
    }
    return mCache.observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
  }
 /**
  * * RxJavaで一覧取得
  *
  * @return
  */
 public Observable<Weather> request() {
   return Observable.create(
           new Observable.OnSubscribe<String>() {
             @Override
             public void call(Subscriber<? super String> subscriber) {
               String tableName = "Weather";
               NCMBQuery<NCMBObject> query = new NCMBQuery<>(tableName);
               query.setLimit(1);
               query.addOrderByDescending(
                   Base.getContext().getString(R.string.NCMB_sort_column_name));
               List<NCMBObject> results = null;
               try {
                 results = query.find();
               } catch (NCMBException e) {
                 subscriber.onError(e);
               }
               if (results == null) {
                 subscriber.onError(new Exception("データが空"));
                 return;
               }
               NCMBObject object = results.get(0);
               String json = object.getString("weather");
               subscriber.onNext(json);
               subscriber.onCompleted();
             }
           })
       .map(
           new Func1<String, Weather>() {
             @Override
             public Weather call(String json) {
               return new Gson().fromJson(json, Weather.class);
             }
           });
 }
Example #18
0
    @Test
    public void testMaterialize1() {
      // null will cause onError to be triggered before "three" can be returned
      final TestAsyncErrorObservable o1 = new TestAsyncErrorObservable("one", "two", null, "three");

      TestObserver Observer = new TestObserver();
      Observable<Notification<String>> m = Observable.create(materialize(o1));
      m.subscribe(Observer);

      try {
        o1.t.join();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }

      assertFalse(Observer.onError);
      assertTrue(Observer.onCompleted);
      assertEquals(3, Observer.notifications.size());
      assertEquals("one", Observer.notifications.get(0).getValue());
      assertTrue(Observer.notifications.get(0).isOnNext());
      assertEquals("two", Observer.notifications.get(1).getValue());
      assertTrue(Observer.notifications.get(1).isOnNext());
      assertEquals(
          NullPointerException.class, Observer.notifications.get(2).getException().getClass());
      assertTrue(Observer.notifications.get(2).isOnError());
    }
Example #19
0
  @Test
  public void testConcatObservableOfObservables() {
    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);

    final String[] o = {"1", "3", "5", "7"};
    final String[] e = {"2", "4", "6"};

    final Observable<String> odds = Observable.from(o);
    final Observable<String> even = Observable.from(e);

    Observable<Observable<String>> observableOfObservables =
        Observable.create(
            new Observable.OnSubscribeFunc<Observable<String>>() {

              @Override
              public Subscription onSubscribe(Observer<? super Observable<String>> observer) {
                // simulate what would happen in an observable
                observer.onNext(odds);
                observer.onNext(even);
                observer.onCompleted();

                return Subscriptions.empty();
              }
            });
    Observable<String> concat = Observable.concat(observableOfObservables);

    concat.subscribe(observer);

    verify(observer, times(7)).onNext(anyString());
  }
Example #20
0
  public static void test5() {
    log("test zip of two observables with equal elements from both lists");
    Observable.zip(
            Observable.from(Arrays.asList(1, 3, 5, 7, 9)),
            Observable.from(Arrays.asList(2, 4, 6, 8, 10)),
            (x, y) -> "(" + x + "," + y + ")")
        .subscribe(Main::print);
    println("");

    log("test zipWith with unequal elements from lists");
    Observable.from(Arrays.asList(1, 3, 5))
        .zipWith(Observable.from(Arrays.asList(2, 4, 6, 7)), (x, y) -> "(" + x + "," + y + ")")
        .subscribe(Main::print);
    println("");

    log("test retry stuff");
    AtomicInteger i = new AtomicInteger(0);
    Observable<String> testRetry =
        Observable.create(
            subs -> {
              if (i.get() < 3) {
                i.incrementAndGet();
                println("retyring for " + i + " time.");
                subs.onError(new RuntimeException("error 1"));
              } else {
                subs.onNext("hello");
                subs.onCompleted();
              }
            });
    testRetry.retry().subscribe(Main::print, Main::println);
    println("");
  }
Example #21
0
  @Test
  public void testUnsubscribeAfterTake() {
    final Subscription s = mock(Subscription.class);
    TestObservableFunc f = new TestObservableFunc("one", "two", "three");
    Observable<String> w = Observable.create(f);

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);

    Subscriber<String> subscriber = Subscribers.from(observer);
    subscriber.add(s);

    Observable<String> take = w.lift(new OperatorTake<String>(1));
    take.subscribe(subscriber);

    // wait for the Observable to complete
    try {
      f.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(observer, times(1)).onCompleted();
    verify(s, times(1)).unsubscribe();
    verifyNoMoreInteractions(observer);
  }
Example #22
0
    @Test
    public void testZippingDifferentLengthObservableSequences2() {
      @SuppressWarnings("unchecked")
      Observer<String> w = mock(Observer.class);

      TestObservable w1 = new TestObservable();
      TestObservable w2 = new TestObservable();
      TestObservable w3 = new TestObservable();

      Observable<String> zipW = Observable.create(zip(w1, w2, w3, getConcat3StringsZipr()));
      zipW.subscribe(w);

      /* simulate sending data */
      // 4 times for w1
      w1.Observer.onNext("1a");
      w1.Observer.onNext("1b");
      w1.Observer.onNext("1c");
      w1.Observer.onNext("1d");
      w1.Observer.onCompleted();
      // twice for w2
      w2.Observer.onNext("2a");
      w2.Observer.onNext("2b");
      w2.Observer.onCompleted();
      // 1 times for w3
      w3.Observer.onNext("3a");
      w3.Observer.onCompleted();

      /* we should have been called 1 time on the Observer */
      InOrder inOrder = inOrder(w);
      inOrder.verify(w).onNext("1a2a3a");

      inOrder.verify(w, times(1)).onCompleted();
    }
Example #23
0
 Object apply(
     final Object[] args, final TProtocol protocol, final int seqid, Scheduler subscribScheduler)
     throws Exception {
   if (isObservable) {
     Observable observable =
         Observable.create(
             new Observable.OnSubscribe<Object>() {
               @Override
               public void call(Subscriber<? super Object> subscriber) {
                 try {
                   if (subscriber.isUnsubscribed()) {
                     return;
                   }
                   subscriber.onNext(FunctionCall.this.sendAndRecv(args, protocol, seqid));
                   subscriber.onCompleted();
                 } catch (Exception e) {
                   subscriber.onError(e);
                 }
               }
             });
     if (null != subscribScheduler) return observable.subscribeOn(subscribScheduler);
     else return observable;
   }
   return sendAndRecv(args, protocol, seqid);
 }
Example #24
0
  public static void main(String[] args) {

    // A basic Observable that emits "Hello World" when someone subscribes to it
    Observable<String> simpleObservable =
        Observable.create(
            new Observable.OnSubscribe<String>() {

              @Override
              public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("Hello, world");
                subscriber.onCompleted();
              }
            });

    // A basic Subscriber to consume the data. All it does is emit a string emitted by the
    // observable
    Subscriber<String> simpleSubscriber =
        new Subscriber<String>() {
          @Override
          public void onCompleted() {}

          @Override
          public void onError(Throwable throwable) {}

          @Override
          public void onNext(String s) {
            System.out.println(s);
          }
        };

    simpleObservable.subscribe(simpleSubscriber);
  }
Example #25
0
 /**
  * Create an observable of child attach state change events on {@code recyclerView}.
  *
  * <p><em>Warning:</em> The created observable keeps a strong reference to {@code recyclerView}.
  * Unsubscribe to free this reference.
  */
 @CheckResult
 @NonNull
 public static Observable<RecyclerViewChildAttachStateChangeEvent> childAttachStateChangeEvents(
     @NonNull RecyclerView view) {
   checkNotNull(view, "view == null");
   return Observable.create(new RecyclerViewChildAttachStateChangeEventOnSubscribe(view));
 }
  public Observable<GameServer> refreshFavourites() {
    return Observable.create(
        subscriber -> {
          new Thread(
                  () -> {
                    favourites.forEach(
                        x -> {
                          gameService
                              .getServerStatus(new Tuple(x.getIp(), x.getPort()))
                              .subscribe(
                                  s -> {
                                    if (!subscriber.isUnsubscribed()) {
                                      subscriber.onNext(
                                          ServerStatusParser.statusToServer(
                                              (String[]) s, new Tuple(x.getIp(), x.getPort())));
                                    }
                                  });
                        });

                    if (!subscriber.isUnsubscribed()) {
                      subscriber.onCompleted();
                    }
                  })
              .start();
        });
  }
Example #27
0
  Observable<Integer> ASYNC_OBSERVABLE_OF_INFINITE_INTEGERS(final CountDownLatch latch) {
    return Observable.create(
        new OnSubscribe<Integer>() {

          @Override
          public void call(final Subscriber<? super Integer> o) {
            Thread t =
                new Thread(
                    new Runnable() {

                      @Override
                      public void run() {
                        System.out.println("-------> subscribe to infinite sequence");
                        System.out.println("Starting thread: " + Thread.currentThread());
                        int i = 1;
                        while (!o.isUnsubscribed()) {
                          o.onNext(i++);
                          Thread.yield();
                        }
                        o.onCompleted();
                        latch.countDown();
                        System.out.println("Ending thread: " + Thread.currentThread());
                      }
                    });
            t.start();
          }
        });
  }
Example #28
0
    @Test
    public void testMaterialize2() {
      final TestAsyncErrorObservable o1 = new TestAsyncErrorObservable("one", "two", "three");

      TestObserver Observer = new TestObserver();
      Observable<Notification<String>> m = Observable.create(materialize(o1));
      m.subscribe(Observer);

      try {
        o1.t.join();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }

      assertFalse(Observer.onError);
      assertTrue(Observer.onCompleted);
      assertEquals(4, Observer.notifications.size());
      assertEquals("one", Observer.notifications.get(0).getValue());
      assertTrue(Observer.notifications.get(0).isOnNext());
      assertEquals("two", Observer.notifications.get(1).getValue());
      assertTrue(Observer.notifications.get(1).isOnNext());
      assertEquals("three", Observer.notifications.get(2).getValue());
      assertTrue(Observer.notifications.get(2).isOnNext());
      assertTrue(Observer.notifications.get(3).isOnCompleted());
    }
Example #29
0
  @Test(timeout = 2000)
  public void testMultiTake() {
    final AtomicInteger count = new AtomicInteger();
    Observable.create(
            new OnSubscribe<Integer>() {

              @Override
              public void call(Subscriber<? super Integer> s) {
                for (int i = 0; !s.isUnsubscribed(); i++) {
                  System.out.println("Emit: " + i);
                  count.incrementAndGet();
                  s.onNext(i);
                }
              }
            })
        .take(100)
        .take(1)
        .toBlocking()
        .forEach(
            new Action1<Integer>() {

              @Override
              public void call(Integer t1) {
                System.out.println("Receive: " + t1);
              }
            });

    assertEquals(1, count.get());
  }
Example #30
0
  @Test
  public void concatVeryLongObservableOfObservablesTakeHalf() {
    final int n = 10000;
    Observable<Observable<Integer>> source =
        Observable.create(
            new OnSubscribe<Observable<Integer>>() {
              @Override
              public void call(Subscriber<? super Observable<Integer>> s) {
                for (int i = 0; i < n; i++) {
                  if (s.isUnsubscribed()) {
                    return;
                  }
                  s.onNext(Observable.from(i));
                }
                s.onCompleted();
              }
            });

    Observable<List<Integer>> result = Observable.concat(source).take(n / 2).toList();

    Observer<List<Integer>> o = mock(Observer.class);
    InOrder inOrder = inOrder(o);

    result.subscribe(o);

    List<Integer> list = new ArrayList<Integer>(n);
    for (int i = 0; i < n / 2; i++) {
      list.add(i);
    }
    inOrder.verify(o).onNext(list);
    inOrder.verify(o).onCompleted();
    verify(o, never()).onError(any(Throwable.class));
  }