io.reactivex.subjects.PublishSubject Java Examples

The following examples show how to use io.reactivex.subjects.PublishSubject. 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: SubscriberEvent.java    From SweetMusicPlayer with Apache License 2.0 6 votes vote down vote up
private void initObservable() {
    subject = PublishSubject.create();
    subject.observeOn(EventThread.getScheduler(thread))
            .subscribe(new Consumer() {
                @Override
                public void accept(Object event) {
                    try {
                        if (valid) {
                            handleEvent(event);
                        }
                    } catch (InvocationTargetException e) {
                        throwRuntimeException("Could not dispatch event: " + event.getClass() + " to subscriber " + SubscriberEvent.this, e);
                    }
                }
            });
}
 
Example #2
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 6 votes vote down vote up
@Test
@TargetApi(Build.VERSION_CODES.M)
public void subscription_trigger_granted() {
    TestObserver<Boolean> sub = new TestObserver<>();
    String permission = Manifest.permission.READ_PHONE_STATE;
    when(mRxPermissions.isGranted(permission)).thenReturn(false);
    int[] result = new int[]{PackageManager.PERMISSION_GRANTED};
    PublishSubject<Object> trigger = PublishSubject.create();

    trigger.compose(mRxPermissions.ensure(permission)).subscribe(sub);
    trigger.onNext(1);
    mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result);

    sub.assertNoErrors();
    sub.assertNotTerminated();
    sub.assertValue(true);
}
 
Example #3
Source File: FlatMapWithTwoErrors.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void innerCancelled4() {
    PublishSubject<Integer> pp1 = PublishSubject.create();
    PublishSubject<Integer> pp2 = PublishSubject.create();
    
    pp1
    .concatMap(v -> pp2)
    .test();

    pp1.onNext(1);
    assertTrue("No subscribers?", pp2.hasObservers());

    pp1.onError(new Exception());
    
    assertFalse("Has subscribers?", pp2.hasObservers());
}
 
Example #4
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 6 votes vote down vote up
@Test
@TargetApi(Build.VERSION_CODES.M)
public void eachSubscription_trigger_granted() {
    TestObserver<Permission> sub = new TestObserver<>();
    String permission = Manifest.permission.READ_PHONE_STATE;
    when(mRxPermissions.isGranted(permission)).thenReturn(false);
    int[] result = new int[]{PackageManager.PERMISSION_GRANTED};
    PublishSubject<Object> trigger = PublishSubject.create();

    trigger.compose(mRxPermissions.ensureEach(permission)).subscribe(sub);
    trigger.onNext(1);
    mRxPermissions.onRequestPermissionsResult(new String[]{permission}, result);

    sub.assertNoErrors();
    sub.assertNotTerminated();
    sub.assertValue(new Permission(permission, true));
}
 
Example #5
Source File: RxTiPresenterUtilsTest.java    From ThirtyInch with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeliverLatestToView_ViewComesAndGoes() throws Exception {
    mPresenter.create();

    PublishSubject<Integer> source = PublishSubject.create();
    TestObserver<Integer> testObserver = new TestObserver<>();

    source
            .compose(RxTiPresenterUtils.<Integer>deliverLatestToView(mPresenter))
            .subscribe(testObserver);

    source.onNext(1);
    source.onNext(2);
    mPresenter.attachView(mView);
    source.onNext(3);
    mPresenter.detachView();
    source.onNext(4);
    source.onNext(5);
    mPresenter.attachView(mView);
    source.onNext(6);

    testObserver.assertNotComplete();
    testObserver.assertNoErrors();
    testObserver.assertValuesOnly(2, 3, 5, 6);
}
 
Example #6
Source File: AvoidOnResultFragment.java    From AvoidOnResult with Apache License 2.0 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //rxjava方式的处理
    PublishSubject<ActivityResultInfo> subject = mSubjects.remove(requestCode);
    if (subject != null) {
        subject.onNext(new ActivityResultInfo(resultCode, data));
        subject.onComplete();
    }

    //callback方式的处理
    AvoidOnResult.Callback callback = mCallbacks.remove(requestCode);
    if (callback != null) {
        callback.onActivityResult(resultCode, data);
    }
}
 
Example #7
Source File: ProcessConsole.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
private void monitor(InputStream input, PublishSubject<String> subject) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input, encoding));
    final int BUFFERSIZE = 4096;
    char[] buffer = new char[BUFFERSIZE];
    while (true) {
        try {
            if (Thread.interrupted()) {
                subject.onComplete();
                return;
            }
            int read = reader.read(buffer, 0, BUFFERSIZE);
            if (read == -1) {
                subject.onComplete();
                return;
            }

            subject.onNext(new String(buffer, 0, read));
        } catch (IOException e) {
            subject.onError(e);
            return;
        }
    }
}
 
Example #8
Source File: JobManagerTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStderrUpdatesEchoesUpdatesFromExecutorObservers() throws InterruptedException, ExecutionException, TimeoutException {
    final CancelablePromise<JobExecutionResult> executorPromise = new SimpleCancelablePromise<>();
    final Subject<byte[]> stderrSubject = PublishSubject.create();
    final JobExecutor executor =
            MockJobExecutor.thatUses(executorPromise, Observable.just(TestHelpers.generateRandomBytes()), stderrSubject);
    final JobManager jobManager = createManagerWith(executor);

    final Pair<JobId, CancelablePromise<FinalizedJob>> ret =
            jobManager.submit(STANDARD_VALID_REQUEST);

    final Observable<byte[]> stderrObservable =
            jobManager.stderrUpdates(ret.getLeft()).get();

    final AtomicReference<byte[]> bytesFromObservable = new AtomicReference<>();
    stderrObservable.subscribe(bytesFromObservable::set);

    final byte[] bytesExpected = TestHelpers.generateRandomBytes();
    stderrSubject.onNext(bytesExpected);

    executorPromise.complete(new JobExecutionResult(FINISHED));

    ret.getRight().get(DEFAULT_TIMEOUT, MILLISECONDS);

    assertThat(bytesFromObservable.get()).isEqualTo(bytesExpected);
}
 
Example #9
Source File: JobManagerTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStdoutUpdatesEchoesUpdatesFromExecutorObservers() throws InterruptedException, ExecutionException, TimeoutException {
    final CancelablePromise<JobExecutionResult> executorPromise = new SimpleCancelablePromise<>();
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    final JobExecutor executor =
            MockJobExecutor.thatUses(executorPromise, stdoutSubject, Observable.just(TestHelpers.generateRandomBytes()));
    final JobManager jobManager = createManagerWith(executor);

    final Pair<JobId, CancelablePromise<FinalizedJob>> ret =
            jobManager.submit(STANDARD_VALID_REQUEST);

    final Observable<byte[]> stdoutObservable =
            jobManager.stdoutUpdates(ret.getLeft()).get();

    final AtomicReference<byte[]> bytesFromObservable = new AtomicReference<>();
    stdoutObservable.subscribe(bytesFromObservable::set);

    final byte[] bytesExpected = TestHelpers.generateRandomBytes();
    stdoutSubject.onNext(bytesExpected);

    executorPromise.complete(new JobExecutionResult(FINISHED));

    ret.getRight().get(DEFAULT_TIMEOUT, MILLISECONDS);

    assertThat(bytesFromObservable.get()).isEqualTo(bytesExpected);
}
 
Example #10
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldAutoResubscribeAfterUnlock() throws InterruptedException {
  ObservableGroup group = observableManager.newGroup();
  TestObserver<String> testObserver = new TestObserver<>();
  PublishSubject<String> sourceObservable = PublishSubject.create();

  group.lock();
  sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver);

  sourceObservable.onNext("Chespirito");
  sourceObservable.onComplete();

  group.unlock();

  testObserver.assertComplete();
  testObserver.assertNoErrors();
  testObserver.assertValue("Chespirito");
  assertThat(group.hasObservables(fooObserver)).isEqualTo(false);
}
 
Example #11
Source File: MobiusEffectRouterTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void effectHandlersShouldBeImmutable() throws Exception {
  // redo some test setup for test case specific conditions
  publishSubject = PublishSubject.create();
  testSubscriber = TestObserver.create();

  SubtypeEffectHandlerBuilder<TestEffect, TestEvent> builder =
      RxMobius.<TestEffect, TestEvent>subtypeEffectHandler()
          .addTransformer(A.class, (Observable<A> as) -> as.map(a -> AEvent.create(a.id())));

  ObservableTransformer<TestEffect, TestEvent> router = builder.build();

  // this should not lead to the effects router being capable of handling B effects
  builder.addTransformer(B.class, bs -> bs.map(b -> BEvent.create(b.id())));

  publishSubject.compose(router).subscribe(testSubscriber);

  B effect = B.create(84);
  publishSubject.onNext(effect);
  publishSubject.onComplete();

  testSubscriber.awaitTerminalEvent();
  testSubscriber.assertError(new UnknownEffectException(effect));
}
 
Example #12
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldQueueMultipleRequests() throws Exception {
  ObservableGroup group = observableManager.newGroup();
  PublishSubject<String> subject1 = PublishSubject.create();
  TestObserver<String> testSubscriber1 = new TestObserver<>();
  PublishSubject<String> subject2 = PublishSubject.create();
  TestObserver<String> testSubscriber2 = new TestObserver<>();

  subject1.compose(group.transform(testSubscriber1)).subscribe(testSubscriber1);
  subject2.compose(group.transform(testSubscriber2)).subscribe(testSubscriber2);
  group.dispose();

  subject1.onNext("Chespirito");
  subject1.onComplete();
  subject2.onNext("Edgar Vivar");
  subject2.onComplete();

  testSubscriber1.assertNotComplete();
  testSubscriber2.assertNotComplete();
  assertThat(group.hasObservables(testSubscriber1)).isEqualTo(true);
  assertThat(group.hasObservables(testSubscriber2)).isEqualTo(true);
}
 
Example #13
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldNotRemoveSubscribersForOtherIds() throws Exception {
  ObservableGroup group = observableManager.newGroup();
  ObservableGroup group2 = observableManager.newGroup();
  PublishSubject<String> subject1 = PublishSubject.create();
  TestAutoResubscribingObserver testSubscriber1 = new TestAutoResubscribingObserver("foo");
  PublishSubject<String> subject2 = PublishSubject.create();
  TestAutoResubscribingObserver testSubscriber2 = new TestAutoResubscribingObserver("bar");

  subject1.compose(group.transform(testSubscriber1)).subscribe(testSubscriber1);
  subject2.compose(group2.transform(testSubscriber2)).subscribe(testSubscriber2);
  group.dispose();

  subject1.onNext("Florinda Mesa");
  subject1.onComplete();
  subject2.onNext("Carlos Villagran");
  subject2.onComplete();

  testSubscriber1.assertionTarget.assertNotComplete();
  testSubscriber2.assertionTarget.assertNoErrors();
  testSubscriber2.assertionTarget.assertValue("Carlos Villagran");
}
 
Example #14
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteStderrListenerIsCompletedOnceApplicationExecutionEnds() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final AtomicBoolean completedCalled = new AtomicBoolean(false);
    final Subject<byte[]> stderrSubject = PublishSubject.create();
    stderrSubject.doOnComplete(() -> completedCalled.set(true)).subscribe();
    final JobEventListeners listeners = createStderrListener(stderrSubject);
    final CancelablePromise<JobExecutionResult> ret =
            jobExecutor.execute(STANDARD_REQUEST, listeners);

    promiseAssert(ret, result -> {
        try {
            // The stderr thread can race with the exit thread
            Thread.sleep(50);
            assertThat(completedCalled.get()).isTrue();
        } catch (InterruptedException ignored) {}
    });
}
 
Example #15
Source File: GroupLifecycleManagerTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void testNonResubscribableObservablesRemovedAfterNonFinishingDestroy() {
  when(observableManager.newGroup()).thenReturn(new ObservableGroup(1));

  GroupLifecycleManager lifecycleManager = GroupLifecycleManager.onCreate
      (observableManager, null, target);

  TestObserver<String> nonResubscribableObserver = new TestObserver<>();
  PublishSubject.<String>create()
      .compose(lifecycleManager.group().transform(nonResubscribableObserver))
      .subscribe(nonResubscribableObserver);

  assertThat(lifecycleManager.group().hasObservables(nonResubscribableObserver)).isTrue();

  //Simulate a rotation
  Activity activity = mock(Activity.class);
  when(activity.isFinishing()).thenReturn(false);
  lifecycleManager.onSaveInstanceState(new Bundle());
  lifecycleManager.onDestroy(activity);

  assertThat(lifecycleManager.group().hasObservables(nonResubscribableObserver)).isFalse();
}
 
Example #16
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldReplaceObservablesOfSameTagAndSameGroupId() {
  ObservableGroup group = observableManager.newGroup();
  PublishSubject<String> observable1 = PublishSubject.create();
  PublishSubject<String> observable2 = PublishSubject.create();
  TestAutoResubscribingObserver observer1 = new TestAutoResubscribingObserver("foo");
  TestAutoResubscribingObserver observer2 = new TestAutoResubscribingObserver("foo");
  observable1.compose(group.transform(observer1)).subscribe(observer1);
  observable2.compose(group.transform(observer2)).subscribe(observer2);

  assertThat(group.subscription(fooObserver).isCancelled()).isFalse();
  assertThat(group.hasObservables(fooObserver)).isTrue();

  observable1.onNext("Hello World 1");
  observable1.onComplete();

  observable2.onNext("Hello World 2");
  observable2.onComplete();

  observer2.assertionTarget.awaitTerminalEvent();
  observer2.assertionTarget.assertComplete();
  observer2.assertionTarget.assertValue("Hello World 2");

  observer1.assertionTarget.assertNoValues();
}
 
Example #17
Source File: ReplayExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 6 votes vote down vote up
private void doSomeWork() {

        PublishSubject<Integer> source = PublishSubject.create();
        ConnectableObservable<Integer> connectableObservable = source.replay(3); // bufferSize = 3 to retain 3 values to replay
        connectableObservable.connect(); // connecting the connectableObservable

        connectableObservable.subscribe(getFirstObserver());

        source.onNext(1);
        source.onNext(2);
        source.onNext(3);
        source.onNext(4);
        source.onComplete();

        /*
         * it will emit 2, 3, 4 as (count = 3), retains the 3 values for replay
         */
        connectableObservable.subscribe(getSecondObserver());

    }
 
Example #18
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesJoinAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${join(',', inputs.someList)}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(stringFromStdout).isEqualTo("a,b,c,d"); // From the input fixture
}
 
Example #19
Source File: AdamantBalanceUpdateService.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
private void startListenBalance(final PublishSubject<Object> subject){
    Disposable subscribe =
            api
                .updateBalance()
                .repeatWhen((completed) -> completed.delay(
                        BuildConfig.UPDATE_BALANCE_SECONDS_DELAY,
                        TimeUnit.SECONDS
                ))
                .retryWhen((completed) -> completed.delay(
                        BuildConfig.UPDATE_BALANCE_SECONDS_DELAY,
                        TimeUnit.SECONDS
                ))
                .repeatWhen(repeatHandler ->
                        repeatHandler.flatMap(nothing -> subject.toFlowable(BackpressureStrategy.LATEST)))
                .subscribe();

    compositeDisposable.add(subscribe);
}
 
Example #20
Source File: ObservableGroupTest.java    From RxGroups with Apache License 2.0 6 votes vote down vote up
@Test public void shouldDeliverQueuedEventsWhenResubscribed() throws Exception {
  ObservableGroup group = observableManager.newGroup();
  TestAutoResubscribingObserver resubscribingObserver = new TestAutoResubscribingObserver("foo");
  PublishSubject<String> sourceObservable = PublishSubject.create();
  sourceObservable.compose(group.transform(resubscribingObserver))
      .subscribe(resubscribingObserver);
  group.dispose();

  sourceObservable.onNext("Hello World");
  sourceObservable.onComplete();

  resubscribingObserver.assertionTarget.assertNotComplete();
  resubscribingObserver.assertionTarget.assertNoValues();

  // TestObserver cannot be reused after being disposed in RxJava2
  resubscribingObserver = new TestAutoResubscribingObserver("foo");
  group.observable(resubscribingObserver).subscribe(resubscribingObserver);

  resubscribingObserver.assertionTarget.assertComplete();
  resubscribingObserver.assertionTarget.assertValue("Hello World");
  assertThat(group.hasObservables(resubscribingObserver)).isEqualTo(false);
}
 
Example #21
Source File: RxWebAuthClientImpl.java    From samples-android with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<RxResult> registerListener(FragmentActivity activity) {
    submitResults = PublishSubject.create();

    registerActivityLifeCycle(activity);
    mSyncAuthClient.registerCallbackIfInterrupt(activity, (result, type) -> {
        switch (type) {
            case SIGN_IN:
                processLogInResult(result);
                break;
            case SIGN_OUT:
                processSignOutResult(result);
                break;
            default:
                break;
        }
    }, Executors.newSingleThreadExecutor());

    return submitResults;
}
 
Example #22
Source File: RealRxPermission.java    From RxPermission with Apache License 2.0 5 votes vote down vote up
@NonNull @CheckReturnValue @TargetApi(M) Observable<Permission> requestOnM(@NonNull final String... permissions) {
  final List<Observable<Permission>> list = new ArrayList<>(permissions.length);
  final List<String> unrequestedPermissions = new ArrayList<>();

  // In case of multiple permissions, we create an observable for each of them.
  // At the end, the observables are combined to have a unique response.

  for (final String permission : permissions) {
    if (isGranted(permission)) {
      list.add(Observable.just(Permission.granted(permission)));
    } else if (isRevokedByPolicy(permission)) {
      list.add(Observable.just(Permission.revokedByPolicy(permission)));
    } else {
      PublishSubject<Permission> subject = currentPermissionRequests.get(permission);

      // Create a new subject if not exists
      if (subject == null) {
        unrequestedPermissions.add(permission);
        subject = PublishSubject.create();
        currentPermissionRequests.put(permission, subject);
      }

      list.add(subject);
    }
  }

  if (!unrequestedPermissions.isEmpty()) {
    final String[] permissionsToRequest = unrequestedPermissions.toArray(new String[0]);
    startShadowActivity(permissionsToRequest);
  }

  return Observable.concat(Observable.fromIterable(list));
}
 
Example #23
Source File: TakeUntil.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    PublishSubject publishSubject = PublishSubject.create();

    Disposable disposable = Single.timer(1000 * 2, TimeUnit.MILLISECONDS)
            .takeUntil(publishSubject.firstOrError())
            .subscribe(
                    data -> System.out.println("ted"),
                    throwable -> System.err.println("ted" + throwable.toString())
            );
    disposable.dispose();

    publishSubject.onNext(1); // emit end of lifecycle
}
 
Example #24
Source File: EpicMiddleware.java    From reductor with Apache License 2.0 5 votes vote down vote up
@Override
public Dispatcher create(Store<T> store, Dispatcher nextDispatcher) {
    PublishSubject<Action> actions = PublishSubject.create();
    disposable = epic.run(actions, store).subscribe(store::dispatch);
    return action -> {
        nextDispatcher.dispatch(action);
        if(action instanceof Action) {
            actions.onNext((Action) action);
        }
    };
}
 
Example #25
Source File: RxDownloader.java    From RxDownloader with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0L);
    PublishSubject<String> publishSubject = subjectMap.get(id);

    if (publishSubject == null)
        return;

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(id);
    DownloadManager downloadManager = getDownloadManager();
    Cursor cursor = downloadManager.query(query);

    if (!cursor.moveToFirst()) {
        cursor.close();
        downloadManager.remove(id);
        publishSubject.onError(new IllegalStateException("Cursor empty, this shouldn't happened"));
        subjectMap.remove(id);
        return;
    }

    int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {
        cursor.close();
        downloadManager.remove(id);
        publishSubject.onError(new IllegalStateException("Download Failed"));
        subjectMap.remove(id);
        return;
    }

    int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
    String downloadedPackageUriString = cursor.getString(uriIndex);
    cursor.close();

    publishSubject.onNext(downloadedPackageUriString);
    publishSubject.onComplete();
    subjectMap.remove(id);
}
 
Example #26
Source File: RibActivityTest.java    From RIBs with Apache License 2.0 5 votes vote down vote up
@Test
public void rxActivity_delaySubscription_shouldIgnoreOtherEvents() {
  ActivityController<EmptyActivity> activityController = buildActivity(EmptyActivity.class);
  final RibActivity activity = activityController.get();

  final PublishSubject<Object> subject = PublishSubject.create();
  AndroidRecordingRx2Observer<Object> o = new AndroidRecordingRx2Observer<>();
  subject
      .hide()
      .delaySubscription(
          activity
              .lifecycle()
              .filter(
                  new Predicate<ActivityLifecycleEvent>() {
                    @Override
                    public boolean test(ActivityLifecycleEvent activityEvent) throws Exception {
                      return activityEvent.getType() == ActivityLifecycleEvent.Type.RESUME;
                    }
                  }))
      .subscribe(o);

  subject.onNext(new Object());
  activityController.create();
  subject.onNext(new Object());
  o.assertNoMoreEvents();
  activityController.start();
  subject.onNext(new Object());
  o.assertNoMoreEvents();
  activityController.postCreate(null);
  subject.onNext(new Object());
  o.assertNoMoreEvents();
  activityController.resume();
  subject.onNext(new Object());
  assertThat(o.takeNext()).isNotNull();
  o.assertNoMoreEvents();
}
 
Example #27
Source File: AbstractSingleToFutureConverterTest.java    From future-converter with Apache License 2.0 5 votes vote down vote up
@Test
public void cancelShouldUnsubscribe() {
    PublishSubject<String> single = PublishSubject.create();
    assertFalse(single.hasObservers());

    T future = toFuture(single.singleOrError());
    assertTrue(single.hasObservers());

    future.cancel(true);

    assertFalse(single.hasObservers());
}
 
Example #28
Source File: ThrottleLastLeak.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Disposable d = PublishSubject.create()
    .throttleLast(100, TimeUnit.MILLISECONDS)
    .subscribe(System.out::println);
    
    Thread.sleep(10000);
    
    d.dispose();
    
    Thread.sleep(1000000);
}
 
Example #29
Source File: NYPublisher.java    From NYBus with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the publisher with scheduler provider and consumer provider.
 *
 * @param schedulerProvider the {@link SchedulerProvider}
 * @param consumerProvider  the {@link ConsumerProvider}
 */
@Override
public void initPublishers(SchedulerProvider schedulerProvider,
                           ConsumerProvider consumerProvider) {
    postingThreadPublisher = PublishSubject.create();
    mainThreadPublisher = PublishSubject.create();
    iOThreadPublisher = PublishSubject.create();
    computationThreadPublisher = PublishSubject.create();
    trampolineThreadPublisher = PublishSubject.create();
    executorThreadPublisher = PublishSubject.create();
    newThreadPublisher = PublishSubject.create();

    postingThreadPublisher.subscribe(consumerProvider.getPostingThreadConsumer());

    if (schedulerProvider.provideMainThreadScheduler() != null) {
        mainThreadPublisher.observeOn(schedulerProvider.provideMainThreadScheduler())
                .subscribe(consumerProvider.getMainThreadConsumer());
    } else {
        mainThreadPublisher.subscribe(consumerProvider.getMainThreadConsumer());
    }

    iOThreadPublisher.observeOn(schedulerProvider.provideIOScheduler())
            .subscribe(consumerProvider.getIOThreadConsumer());

    computationThreadPublisher.observeOn(schedulerProvider.provideComputationScheduler())
            .subscribe(consumerProvider.getComputationThreadConsumer());

    trampolineThreadPublisher.observeOn(schedulerProvider.provideTrampolineScheduler())
            .subscribe(consumerProvider.getTrampolineThreadConsumer());

    executorThreadPublisher.observeOn(schedulerProvider.provideExecutorScheduler())
            .subscribe(consumerProvider.getExecutorThreadConsumer());

    newThreadPublisher.observeOn(schedulerProvider.provideNewThreadScheduler())
            .subscribe(consumerProvider.getNewThreadConsumer());
}
 
Example #30
Source File: WriteBehindCacheWriter.java    From caffeine with Apache License 2.0 5 votes vote down vote up
private WriteBehindCacheWriter(Builder<K, V> builder) {
  subject = PublishSubject.create();
  subject.buffer(builder.bufferTimeNanos, TimeUnit.NANOSECONDS)
      .map(entries -> entries.stream().collect(
          toMap(Entry::getKey, Entry::getValue, builder.coalescer)))
      .subscribe(builder.writeAction::accept);
}