Java Code Examples for rx.subjects.PublishSubject#onCompleted()

The following examples show how to use rx.subjects.PublishSubject#onCompleted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FlatMapCompletableTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void invokesTheActionThenCompletesAndEmitsNothing() throws Exception {
  PublishSubject<Integer> values = PublishSubject.create();

  SideEffectPerformer sideEffectPerformer = new SideEffectPerformer();
  FlatMapCompletable<Integer, SomeOtherType> flatMapCompletable =
      FlatMapCompletable.createForAction(sideEffectPerformer);

  Observable<SomeOtherType> observable = values.compose(flatMapCompletable);

  TestSubscriber<SomeOtherType> subscriber = new TestSubscriber<>();
  observable.subscribe(subscriber);

  values.onNext(1);
  values.onNext(5);
  values.onNext(6);
  List<Integer> unaffectedValues = sideEffectPerformer.verifySideEffects(1, 5, 6);
  assertTrue(unaffectedValues.isEmpty());
  subscriber.assertNoValues();

  values.onCompleted();
  subscriber.assertCompleted();
}
 
Example 2
Source File: RxPermissionsFragment.java    From AndroidProjects with MIT License 6 votes vote down vote up
void onRequestPermissionsResult(String permissions[], int[] grantResults, boolean[] shouldShowRequestPermissionRationale) {
    for (int i = 0, size = permissions.length; i < size; i++) {
        log("onRequestPermissionsResult  " + permissions[i]);
        // Find the corresponding subject
        PublishSubject<Permission> subject = mSubjects.get(permissions[i]);
        if (subject == null) {
            // No subject found
            Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request.");
            return;
        }
        mSubjects.remove(permissions[i]);
        boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
        subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i]));
        subject.onCompleted();
    }
}
 
Example 3
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleSimultaneousSubscriptions() {
    PublishSubject<Integer> subject = PublishSubject.create();
    Recorder recorder1 = new Recorder();
    Recorder recorder2 = new Recorder();
    subject.subscribe(recorder1);
    subject.subscribe(recorder2);
    subject.onNext(1);
    assertEquals(asList(1), recorder1.list());
    assertEquals(asList(1), recorder2.list());
    subject.onNext(2);
    assertEquals(asList(1, 2), recorder1.list());
    assertEquals(asList(1, 2), recorder2.list());
    assertFalse(recorder1.isCompleted());
    assertFalse(recorder2.isCompleted());
    subject.onCompleted();
    assertTrue(recorder1.isCompleted());
    assertTrue(recorder2.isCompleted());
}
 
Example 4
Source File: OperatorSampleFirstTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testSampleWindowIsConstantDuration() {
    @SuppressWarnings("unchecked")
    Observer<Integer> observer = mock(Observer.class);
    TestScheduler s = new TestScheduler();
    PublishSubject<Integer> o = PublishSubject.create();
    o.compose(Transformers.<Integer> sampleFirst(1000, TimeUnit.MILLISECONDS, s))
            .subscribe(observer);

    // send events with simulated time increments
    s.advanceTimeTo(0, TimeUnit.MILLISECONDS);
    o.onNext(1);
    s.advanceTimeTo(1200, TimeUnit.MILLISECONDS);
    o.onNext(2);
    s.advanceTimeTo(2100, TimeUnit.MILLISECONDS);
    o.onNext(3);
    o.onCompleted();

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer).onNext(1);
    inOrder.verify(observer).onNext(2);
    inOrder.verify(observer).onNext(3);
    inOrder.verify(observer).onCompleted();
    inOrder.verifyNoMoreInteractions();
}
 
Example 5
Source File: RemoteObservableTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnCompletedFromReplaySubject() {
    PublishSubject<Integer> subject = PublishSubject.create();
    subject.onNext(1);
    subject.onNext(2);
    subject.onNext(3);
    subject.onCompleted();
    // serve
    PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000);
    int serverPort = portSelector.acquirePort();
    RemoteRxServer server = new RemoteRxServer.Builder()
            .port(serverPort)
            .addObservable(new ServeObservable.Builder<Integer>()
                    .encoder(Codecs.integer())
                    .observable(subject)
                    .serverSideFilter(ServerSideFilters.oddsAndEvens())
                    .build())
            .build();
    server.start();
    // connect
    Observable<Integer> ro = RemoteObservable.connect("localhost", serverPort, Codecs.integer());
    final MutableReference<Boolean> completed = new MutableReference<Boolean>();
    ro.materialize().toBlocking().forEach(new Action1<Notification<Integer>>() {
        @Override
        public void call(Notification<Integer> notification) {
            if (notification.isOnCompleted()) {
                completed.setValue(true);
            }
        }
    });
    Assert.assertEquals(true, completed.getValue());
}
 
Example 6
Source File: RxFacebookAuthFragment.java    From RxSocialAuth with Apache License 2.0 5 votes vote down vote up
/**
 * Facebook sign out
 */
public void signOut(PublishSubject<RxStatus> statusSubject) {
    LoginManager.getInstance().logOut();
    // delete current user
    deleteCurrentUser();
    statusSubject.onNext(new RxStatus(
            CommonStatusCodes.SUCCESS,
            getString(R.string.status_success_log_out_message)
    ));
    statusSubject.onCompleted();
}
 
Example 7
Source File: OperatorSampleFirstTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testSampleFirst() {
    @SuppressWarnings("unchecked")
    Observer<Integer> observer = mock(Observer.class);
    TestScheduler s = new TestScheduler();
    PublishSubject<Integer> o = PublishSubject.create();
    o.compose(Transformers.<Integer> sampleFirst(500, TimeUnit.MILLISECONDS, s))
            .subscribe(observer);

    // send events with simulated time increments
    s.advanceTimeTo(0, TimeUnit.MILLISECONDS);
    o.onNext(1); // deliver
    o.onNext(2); // skip
    s.advanceTimeTo(501, TimeUnit.MILLISECONDS);
    o.onNext(3); // deliver
    s.advanceTimeTo(600, TimeUnit.MILLISECONDS);
    o.onNext(4); // skip
    s.advanceTimeTo(700, TimeUnit.MILLISECONDS);
    o.onNext(5); // skip
    o.onNext(6); // skip
    s.advanceTimeTo(1001, TimeUnit.MILLISECONDS);
    o.onNext(7); // deliver
    s.advanceTimeTo(1501, TimeUnit.MILLISECONDS);
    o.onCompleted();

    InOrder inOrder = inOrder(observer);
    inOrder.verify(observer).onNext(1);
    inOrder.verify(observer).onNext(3);
    inOrder.verify(observer).onNext(7);
    inOrder.verify(observer).onCompleted();
    inOrder.verifyNoMoreInteractions();
}
 
Example 8
Source File: SubjectImpl.java    From tutorials with MIT License 5 votes vote down vote up
private static Integer subjectMethod() {
    PublishSubject<Integer> subject = PublishSubject.create();

    subject.subscribe(getFirstObserver());

    subject.onNext(1);
    subject.onNext(2);
    subject.onNext(3);

    subject.subscribe(getSecondObserver());

    subject.onNext(4);
    subject.onCompleted();
    return subscriber1 + subscriber2;
}
 
Example 9
Source File: SubjectUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() {
    PublishSubject<Integer> subject = PublishSubject.create();

    subject.subscribe(SubjectImpl.getFirstObserver());
    subject.onNext(1);
    subject.onNext(2);
    subject.onNext(3);

    subject.subscribe(SubjectImpl.getSecondObserver());
    subject.onNext(4);
    subject.onCompleted();

    assertTrue(SubjectImpl.subscriber1 + SubjectImpl.subscriber2 == 14);
}
 
Example 10
Source File: ConsistencyWriterTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Test(groups = "unit")
public void startBackgroundAddressRefresh() throws Exception {
    initializeConsistencyWriter(false);

    CyclicBarrier b = new CyclicBarrier(2);
    PublishSubject<Uri> subject = PublishSubject.create();
    CountDownLatch c = new CountDownLatch(1);

    Uri uri = Uri.create("https://localhost:5050");

    List<InvocationOnMock> invocationOnMocks = Collections.synchronizedList(new ArrayList<>());
    Mockito.doAnswer(new Answer() {
        @Override
        public Single<Uri> answer(InvocationOnMock invocationOnMock)  {
            invocationOnMocks.add(invocationOnMock);
            return subject.toSingle().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            b.await();
                        } catch (Exception e) {

                        }
                    }
                }.start();
            });
        }
    }).when(addressSelector).resolvePrimaryUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean());
    RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class);
    consistencyWriter.startBackgroundAddressRefresh(request);

    subject.onNext(uri);
    subject.onCompleted();

    TimeUnit.MILLISECONDS.sleep(1000);
    assertThat(c.getCount()).isEqualTo(0);
    assertThat(b.getNumberWaiting()).isEqualTo(1);
    b.await(1000, TimeUnit.MILLISECONDS);
    assertThat(invocationOnMocks).hasSize(1);
    assertThat(invocationOnMocks.get(0).getArgumentAt(1, Boolean.class)).isTrue();
}
 
Example 11
Source File: StoreReaderTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
/**
 * Tests for {@link StoreReader}
 */
@Test(groups = "unit")
public void startBackgroundAddressRefresh() throws Exception {
    TransportClient transportClient = Mockito.mock(TransportClient.class);
    AddressSelector addressSelector = Mockito.mock(AddressSelector.class);
    ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class);

    StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer);

    CyclicBarrier b = new CyclicBarrier(2);
    PublishSubject<List<Uri>> subject = PublishSubject.create();
    CountDownLatch c = new CountDownLatch(1);

    List<Uri> uris = ImmutableList.of(Uri.create("https://localhost:5050"), Uri.create("https://localhost:5051"),
                                      Uri.create("https://localhost:50502"), Uri.create("https://localhost:5053"));

    Mockito.doAnswer(new Answer() {
        @Override
        public Single<List<Uri>> answer(InvocationOnMock invocationOnMock) throws Throwable {

            return subject.toSingle().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            b.await();
                        } catch (Exception e) {

                        }
                    }
                }.start();
            });
        }
    }).when(addressSelector).resolveAllUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(true), Mockito.eq(true));
    RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class);
    storeReader.startBackgroundAddressRefresh(request);

    subject.onNext(uris);
    subject.onCompleted();

    TimeUnit.MILLISECONDS.sleep(100);
    AssertionsForClassTypes.assertThat(c.getCount()).isEqualTo(0);
    AssertionsForClassTypes.assertThat(b.getNumberWaiting()).isEqualTo(1);
    b.await(1000, TimeUnit.MILLISECONDS);
}
 
Example 12
Source File: RxActivityResult.java    From RxActivityResult with Apache License 2.0 4 votes vote down vote up
void onActivityResult(int requestCode, int resultCode, Intent data) {
    PublishSubject<ActivityResult> subject = results.remove(requestCode);
    ActivityResult result = new ActivityResult(requestCode, resultCode, data);
    subject.onNext(result);
    subject.onCompleted();
}
 
Example 13
Source File: AutoRemoveSubscription.java    From akarnokd-misc with Apache License 2.0 3 votes vote down vote up
@Test
public void test() {
    CompositeSubscription composite = new CompositeSubscription();
    
    PublishSubject<Integer> ps = PublishSubject.create();
    
    subscribeAutoRelease(ps, System.out::println, composite);
    
    Assert.assertTrue(composite.hasSubscriptions());
    
    ps.onNext(1);
    ps.onCompleted();

    Assert.assertFalse(composite.hasSubscriptions());
}