예제 #1
0
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   Observable<Long> deferObservable = DeferObserver();
   Observable<Long> justObservable = JustObserver();
   mLButton.setText("Defer");
   mRButton.setText("Just");
   mLButton.setOnClickListener(e -> deferObservable.subscribe(time -> log("defer:" + time)));
   mRButton.setOnClickListener(e -> justObservable.subscribe(time -> log("just:" + time)));
 }
  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);
              }));
    }
  }
예제 #3
0
  @Test
  public void testFlatMapMaxConcurrent() {
    final int m = 4;
    final AtomicInteger subscriptionCount = new AtomicInteger();
    Observable<Integer> source =
        Observable.range(1, 10)
            .flatMap(
                new Func1<Integer, Observable<Integer>>() {
                  @Override
                  public Observable<Integer> call(Integer t1) {
                    return compose(Observable.range(t1 * 10, 2), subscriptionCount, m)
                        .subscribeOn(Schedulers.computation());
                  }
                },
                m);

    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();

    source.subscribe(ts);

    ts.awaitTerminalEvent();
    ts.assertNoErrors();
    Set<Integer> expected =
        new HashSet<Integer>(
            Arrays.asList(
                10, 11, 20, 21, 30, 31, 40, 41, 50, 51, 60, 61, 70, 71, 80, 81, 90, 91, 100, 101));
    Assert.assertEquals(expected.size(), ts.getOnNextEvents().size());
    Assert.assertTrue(expected.containsAll(ts.getOnNextEvents()));
  }
예제 #4
0
    @Test
    public void testUnsubscribeAfterTake() {
      Subscription s = mock(Subscription.class);
      TestObservable w = new TestObservable(s, "one", "two", "three");

      @SuppressWarnings("unchecked")
      Observer<String> aObserver = mock(Observer.class);
      Observable<String> take = Observable.create(take(w, 1));
      take.subscribe(aObserver);

      // wait for the Observable to complete
      try {
        w.t.join();
      } catch (Throwable e) {
        e.printStackTrace();
        fail(e.getMessage());
      }

      System.out.println("TestObservable thread finished");
      verify(aObserver, times(1)).onNext("one");
      verify(aObserver, never()).onNext("two");
      verify(aObserver, never()).onNext("three");
      verify(aObserver, times(1)).onCompleted();
      verify(s, times(1)).unsubscribe();
      verifyNoMoreInteractions(aObserver);
    }
예제 #5
0
    /**
     * unit test from OperationMergeDelayError backported here to show how these use cases work with
     * normal merge
     */
    @Test
    public void testError2() {
      // we are using synchronous execution to test this exactly rather than non-deterministic
      // concurrent behavior
      final Observable<String> o1 = new TestErrorObservable("one", "two", "three");
      final Observable<String> o2 =
          new TestErrorObservable("four", null, "six"); // we expect to lose "six"
      final Observable<String> o3 =
          new TestErrorObservable(
              "seven", "eight",
              null); // we expect to lose all of these since o2 is done first and fails
      final Observable<String> o4 =
          new TestErrorObservable(
              "nine"); // we expect to lose all of these since o2 is done first and fails

      @SuppressWarnings("unchecked")
      Observable<String> m = Observable.create(merge(o1, o2, o3, o4));
      m.subscribe(stringObserver);

      verify(stringObserver, times(1)).onError(any(NullPointerException.class));
      verify(stringObserver, never()).onCompleted();
      verify(stringObserver, times(1)).onNext("one");
      verify(stringObserver, times(1)).onNext("two");
      verify(stringObserver, times(1)).onNext("three");
      verify(stringObserver, times(1)).onNext("four");
      verify(stringObserver, times(0)).onNext("five");
      verify(stringObserver, times(0)).onNext("six");
      verify(stringObserver, times(0)).onNext("seven");
      verify(stringObserver, times(0)).onNext("eight");
      verify(stringObserver, times(0)).onNext("nine");
    }
예제 #6
0
    @Test
    public void testUnSubscribe() {
      TestObservable tA = new TestObservable();
      TestObservable tB = new TestObservable();

      @SuppressWarnings("unchecked")
      Observable<String> m = Observable.create(merge(tA, tB));
      Subscription s = m.subscribe(stringObserver);

      tA.sendOnNext("Aone");
      tB.sendOnNext("Bone");
      s.unsubscribe();
      tA.sendOnNext("Atwo");
      tB.sendOnNext("Btwo");
      tA.sendOnCompleted();
      tB.sendOnCompleted();

      verify(stringObserver, never()).onError(any(Exception.class));
      verify(stringObserver, times(1)).onNext("Aone");
      verify(stringObserver, times(1)).onNext("Bone");
      assertTrue(tA.unsubscribed);
      assertTrue(tB.unsubscribed);
      verify(stringObserver, never()).onNext("Atwo");
      verify(stringObserver, never()).onNext("Btwo");
      verify(stringObserver, never()).onCompleted();
    }
예제 #7
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");
    }
예제 #8
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();
  }
  @Test
  public void testSingleWithBackpressure() {
    Observable<Integer> observable = Observable.just(1, 2).single();

    Subscriber<Integer> subscriber =
        spy(
            new Subscriber<Integer>() {

              @Override
              public void onStart() {
                request(1);
              }

              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {}

              @Override
              public void onNext(Integer integer) {
                request(1);
              }
            });
    observable.subscribe(subscriber);

    InOrder inOrder = inOrder(subscriber);
    inOrder.verify(subscriber, times(1)).onError(isA(IllegalArgumentException.class));
    inOrder.verifyNoMoreInteractions();
  }
예제 #10
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);
  }
예제 #11
0
  @Test
  public void testEmitNull() {
    Observable<Integer> oi = Observable.from(1, null, 3);
    Observable<String> os = Observable.from("a", "b", null);
    Observable<String> o =
        Observable.zip(
            oi,
            os,
            new Func2<Integer, String, String>() {

              @Override
              public String call(Integer t1, String t2) {
                return t1 + "-" + t2;
              }
            });

    final ArrayList<String> list = new ArrayList<String>();
    o.subscribe(
        new Action1<String>() {

          @Override
          public void call(String s) {
            System.out.println(s);
            list.add(s);
          }
        });

    assertEquals(3, list.size());
    assertEquals("1-a", list.get(0));
    assertEquals("null-b", list.get(1));
    assertEquals("3-null", list.get(2));
  }
  @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();
  }
  @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");
  }
예제 #14
0
  @Test
  public void testSkipTimedFinishBeforeTime() {
    TestScheduler scheduler = new TestScheduler();

    PublishSubject<Integer> source = PublishSubject.create();

    Observable<Integer> result = source.skip(1, TimeUnit.SECONDS, scheduler);

    Observer<Object> o = mock(Observer.class);

    result.subscribe(o);

    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    source.onCompleted();

    scheduler.advanceTimeBy(1, TimeUnit.SECONDS);

    InOrder inOrder = inOrder(o);

    inOrder.verify(o).onCompleted();
    inOrder.verifyNoMoreInteractions();
    verify(o, never()).onNext(any());
    verify(o, never()).onError(any(Throwable.class));
  }
  /** 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(groups = "standalone")
  public void testObserveMultiple() {
    final TestSubscriber<Response> tester = new TestSubscriber<>();

    try (AsyncHttpClient client = asyncHttpClient()) {
      Observable<Response> o1 =
          AsyncHttpObservable.observe(() -> client.prepareGet("http://gatling.io"));
      Observable<Response> o2 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.wisc.edu").setFollowRedirect(true));
      Observable<Response> o3 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.umn.edu").setFollowRedirect(true));
      Observable<Response> all = Observable.merge(o1, o2, o3);
      all.subscribe(tester);
      tester.awaitTerminalEvent();
      tester.assertTerminalEvent();
      tester.assertCompleted();
      tester.assertNoErrors();
      List<Response> responses = tester.getOnNextEvents();
      assertNotNull(responses);
      assertEquals(responses.size(), 3);
      for (Response response : responses) {
        assertEquals(response.getStatusCode(), 200);
      }
    } catch (Exception e) {
      Thread.currentThread().interrupt();
    }
  }
 @Test
 public void testLoadFromCacheExpired() throws Exception {
   fileBytesStore.setExpired(true);
   Observable fromCacheObservable = fileBytesStore.loadFromPersistentCache(KEY);
   fromCacheObservable.subscribe();
   verify(diskCache, never()).readBytes(fileBytesStore.cacheKey(KEY));
 }
예제 #18
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();
    }
예제 #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());
  }
예제 #20
0
  @Test
  public void sampleWithSamplerNoDuplicates() {
    PublishSubject<Integer> source = PublishSubject.create();
    PublishSubject<Integer> sampler = PublishSubject.create();

    Observable<Integer> m = source.sample(sampler);
    m.subscribe(observer2);

    source.onNext(1);
    source.onNext(2);
    sampler.onNext(1);
    sampler.onNext(1);

    source.onNext(3);
    source.onNext(4);
    sampler.onNext(2);
    sampler.onNext(2);

    source.onCompleted();
    sampler.onNext(3);

    InOrder inOrder = inOrder(observer2);
    inOrder.verify(observer2, never()).onNext(1);
    inOrder.verify(observer2, times(1)).onNext(2);
    inOrder.verify(observer2, never()).onNext(3);
    inOrder.verify(observer2, times(1)).onNext(4);
    inOrder.verify(observer2, times(1)).onCompleted();
    verify(observer, never()).onError(any(Throwable.class));
  }
예제 #21
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);
  }
예제 #22
0
  public static void main(String[] args) {
    Common.init("Hello RxJava");

    Observable<String> tweets =
        Observable.just("Hello RxJava!", "RxJava is fun!!", "RxJava rocks!!!");
    tweets.subscribe((s) -> System.out.println(s));
  }
예제 #23
0
  @Test
  public void observeOnTheSameSchedulerTwice() {
    Scheduler scheduler = Schedulers.immediate();

    Observable<Integer> o = Observable.just(1, 2, 3);
    Observable<Integer> o2 = o.observeOn(scheduler);

    @SuppressWarnings("unchecked")
    Observer<Object> observer1 = mock(Observer.class);
    @SuppressWarnings("unchecked")
    Observer<Object> observer2 = mock(Observer.class);

    InOrder inOrder1 = inOrder(observer1);
    InOrder inOrder2 = inOrder(observer2);

    o2.subscribe(observer1);
    o2.subscribe(observer2);

    inOrder1.verify(observer1, times(1)).onNext(1);
    inOrder1.verify(observer1, times(1)).onNext(2);
    inOrder1.verify(observer1, times(1)).onNext(3);
    inOrder1.verify(observer1, times(1)).onCompleted();
    verify(observer1, never()).onError(any(Throwable.class));
    inOrder1.verifyNoMoreInteractions();

    inOrder2.verify(observer2, times(1)).onNext(1);
    inOrder2.verify(observer2, times(1)).onNext(2);
    inOrder2.verify(observer2, times(1)).onNext(3);
    inOrder2.verify(observer2, times(1)).onCompleted();
    verify(observer2, never()).onError(any(Throwable.class));
    inOrder2.verifyNoMoreInteractions();
  }
예제 #24
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();
    }
예제 #25
0
  @Test
  public void testZip() {
    Observable<String> os =
        OBSERVABLE_OF_5_INTEGERS.zip(
            OBSERVABLE_OF_5_INTEGERS,
            new Func2<Integer, Integer, String>() {

              @Override
              public String call(Integer a, Integer b) {
                return a + "-" + b;
              }
            });

    final ArrayList<String> list = new ArrayList<String>();
    os.subscribe(
        new Action1<String>() {

          @Override
          public void call(String s) {
            System.out.println(s);
            list.add(s);
          }
        });

    assertEquals(5, list.size());
    assertEquals("1-1", list.get(0));
    assertEquals("2-2", list.get(1));
    assertEquals("5-5", list.get(4));
  }
예제 #26
0
 public RxMeetupService() {
   this.subject = PublishSubject.<String>create();
   this.meetupClient =
       withTimeout(
               CompletableFuture.supplyAsync(
                   () ->
                       RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("stream.meetup.com", 443)
                           .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
                           .withSslEngineFactory(DefaultFactories.trustAll())
                           .build()),
               Duration.ofSeconds(2))
           .thenApply(
               client -> {
                 log.info("<RxMeetupService> set up meetup subject");
                 final Observable<String> jsons =
                     StringObservable.split(
                         client
                             .submit(HttpClientRequest.createGet("/2/open_events"))
                             .flatMap(AbstractHttpContentHolder::getContent)
                             .map(bb -> bb.toString(StandardCharsets.UTF_8)),
                         "\n");
                 jsons.subscribe(this.subject);
                 return client;
               })
           .exceptionally(
               ex -> { // TODO: timed re-connect
                 log.error("<RxMeetupService> ", ex);
                 this.subject.onError(ex);
                 return null;
               });
 }
예제 #27
0
 public Subscription onSubscribe(Observer<? super T> observer) {
   if (lock == null) {
     atomicObserver = new SynchronizedObserver<T>(observer);
   } else {
     atomicObserver = new SynchronizedObserver<T>(observer, lock);
   }
   return innerObservable.subscribe(atomicObserver);
 }
    public Subscription onSubscribe(final Observer<? super T> observer) {
      final SafeObservableSubscription subscription = new SafeObservableSubscription();

      // AtomicReference since we'll be accessing/modifying this across threads so we can switch it
      // if needed
      final AtomicReference<SafeObservableSubscription> subscriptionRef =
          new AtomicReference<SafeObservableSubscription>(subscription);

      // subscribe to the original Observable and remember the subscription
      subscription.wrap(
          originalSequence.subscribe(
              new Observer<T>() {
                public void onNext(T value) {
                  // forward the successful calls unless resumed
                  if (subscriptionRef.get() == subscription) observer.onNext(value);
                }

                /**
                 * Instead of passing the onError forward, we intercept and "resume" with the
                 * resumeSequence.
                 */
                public void onError(Throwable ex) {
                  /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */
                  SafeObservableSubscription currentSubscription = subscriptionRef.get();
                  // check that we have not been unsubscribed and not already resumed before we can
                  // process the error
                  if (currentSubscription == subscription) {
                    /* error occurred, so switch subscription to the 'resumeSequence' */
                    SafeObservableSubscription innerSubscription =
                        new SafeObservableSubscription(resumeSequence.subscribe(observer));
                    /* we changed the sequence, so also change the subscription to the one of the 'resumeSequence' instead */
                    if (!subscriptionRef.compareAndSet(currentSubscription, innerSubscription)) {
                      // we failed to set which means 'subscriptionRef' was set to NULL via the
                      // unsubscribe below
                      // so we want to immediately unsubscribe from the resumeSequence we just
                      // subscribed to
                      innerSubscription.unsubscribe();
                    }
                  }
                }

                public void onCompleted() {
                  // forward the successful calls unless resumed
                  if (subscriptionRef.get() == subscription) observer.onCompleted();
                }
              }));

      return Subscriptions.create(
          new Action0() {
            public void call() {
              // this will get either the original, or the resumeSequence one and unsubscribe on it
              Subscription s = subscriptionRef.getAndSet(null);
              if (s != null) {
                s.unsubscribe();
              }
            }
          });
    }
예제 #29
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();
  }
  public static void main(String[] args) {
    Observable<String> syncSimpleObservable = Observable.just("a", "b", "c");
    syncSimpleObservable.subscribe(
        new Subscriber<String>() {
          @Override
          public void onCompleted() {
            System.out.println("Finised simple");
          }

          @Override
          public void onError(Throwable throwable) {}

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

    Observable<String> asyncObservable =
        Observable.create(
            new Observable.OnSubscribe<String>() {
              @Override
              public void call(Subscriber<? super String> subscriber) {
                new expensiveThread(subscriber).start();
              }
            });
    asyncObservable.subscribe(
        new Subscriber<String>() {
          @Override
          public void onCompleted() {
            System.out.println("Finished custom");
          }

          @Override
          public void onError(Throwable throwable) {}

          @Override
          public void onNext(String s) {
            System.out.println("Recieved : " + s);
          }
        });
    System.out.println("Main over !");
  }