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

The following examples show how to use rx.subjects.PublishSubject#create() . 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: ListStoreAppsPresenterTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void getAppsAfterRetryClickWithLoading() {
  //Given an initialized ListStoreAppsPresenter with a STORE_ID and a limit of apps
  //When onCreate lifecycle call event happens
  //and the user is on the no network view
  //and clicks on the retry button

  PublishSubject<Void> retryClickEvent = PublishSubject.create();
  when(view.getRetryEvent()).thenReturn(retryClickEvent);
  when(appCenter.loadNextApps(STORE_ID_TEST, LIMIT_APPS_TEST)).thenReturn(
      Single.just(appsModelLoading));
  listStoreAppsPresenter.present();
  lifecycleEvent.onNext(View.LifecycleEvent.CREATE);
  retryClickEvent.onNext(null);

  //then a loading should be shown in the UI
  verify(view).showStartingLoading();
  //and a request apps should be done
  verify(appCenter).loadNextApps(STORE_ID_TEST, LIMIT_APPS_TEST);
  //and apps model is loading
  //hide loading
  verify(view).hideLoading();
  //should do nothing else
  verify(view, never()).showNetworkError();
  verify(view, never()).showGenericError();
  verify(view, never()).addApps(appsModelLoading.getList());
}
 
Example 2
Source File: ListStoreAppsPresenterTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void loadAppsAfterRefreshWithSuccess() {
  //Given an initialized ListStoreAppsPresenter with a STORE_ID and a limit of apps
  //When onCreate lifecycle call event happens
  //and the view is refreshed by the user
  PublishSubject<Void> refreshEvent = PublishSubject.create();
  when(view.getRefreshEvent()).thenReturn(refreshEvent);

  when(appCenter.loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST)).thenReturn(
      Single.just(appsModel));

  listStoreAppsPresenter.present();
  lifecycleEvent.onNext(View.LifecycleEvent.CREATE);
  refreshEvent.onNext(null);

  //Then when new apps are requested loadFreshApps
  verify(appCenter).loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST);
  //and hide the refresh loading
  verify(view).hideRefreshLoading();
  //and show success - add apps list
  verify(view).setApps(appsModel.getList());
}
 
Example 3
Source File: HttpSourceImpl.java    From mantis with Apache License 2.0 6 votes vote down vote up
public Builder(
        HttpClientFactory<R, E> clientFactory,
        HttpRequestFactory<R> requestFactory,
        Func2<ServerContext<HttpClientResponse<E>>, E, T> postProcessor
) {
    this.requestFactory = requestFactory;
    this.httpClientFactory = clientFactory;
    this.serverProvider = EMPTY_HTTP_SERVER_PROVIDER;
    this.postProcessor = postProcessor;

    // Do not resume by default
    this.clientResumePolicy = new ClientResumePolicy<R, E>() {
        @Override
        public Observable<HttpClientResponse<E>> onError(ServerClientContext<R, E> clientContext, int attempts, Throwable error) {
            return null;
        }

        @Override
        public Observable<HttpClientResponse<E>> onCompleted(ServerClientContext<R, E> clientContext, int attempts) {
            return null;
        }
    };

    //			this.clientResumePolicy = ClientResumePolicies.maxRepeat(9);
    observer = PublishSubject.create();
}
 
Example 4
Source File: MobiusEffectRouterTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  cConsumer = new TestConsumer<>();
  dAction = new TestAction();
  Transformer<TestEffect, TestEvent> router =
      RxMobius.<TestEffect, TestEvent>subtypeEffectHandler()
          .addTransformer(A.class, (Observable<A> as) -> as.map(a -> AEvent.create(a.id())))
          .addTransformer(B.class, (Observable<B> bs) -> bs.map(b -> BEvent.create(b.id())))
          .addConsumer(C.class, cConsumer)
          .addAction(D.class, dAction)
          .addFunction(E.class, e -> AEvent.create(e.id()))
          .build();

  publishSubject = PublishSubject.create();
  testSubscriber = TestSubscriber.create();

  publishSubject.compose(router).subscribe(testSubscriber);
}
 
Example 5
Source File: ListStoreAppsPresenterTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void loadAppsAfterRefreshWithGenericError() {
  //Given an initialized ListStoreAppsPresenter with a STORE_ID and a limit of apps
  //When onCreate lifecycle call event happens
  //and the view is refreshed by the user
  PublishSubject<Void> refreshEvent = PublishSubject.create();
  when(view.getRefreshEvent()).thenReturn(refreshEvent);

  when(appCenter.loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST)).thenReturn(
      Single.just(appsModelWithGenericError));

  listStoreAppsPresenter.present();
  lifecycleEvent.onNext(View.LifecycleEvent.CREATE);
  refreshEvent.onNext(null);

  //Then when new apps are requested
  verify(appCenter).loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST);
  //hide refresh loading
  verify(view).hideRefreshLoading();
  // and show Generic error
  verify(view).showGenericError();
}
 
Example 6
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeFromSynchronousSource() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    PublishSubject<Integer> subject = PublishSubject.create();
    subject
            // detect unsubscribe
            .doOnUnsubscribe(countDown(latch))
            // use toOperator
            .lift(toOperator(Functions.<Observable<Integer>> identity()))
            // get first only
            .take(1)
            // subscribe and ignore events
            .subscribe();
    subject.onNext(1);
    // should have unsubscribed because of take(1)
    assertTrue(latch.await(AWAIT_SECONDS, TimeUnit.SECONDS));
}
 
Example 7
Source File: SubscriptionLimiterTest.java    From MarketData with Apache License 2.0 6 votes vote down vote up
@Test
public void should_fail_on_second_subscription() {
    // given
    PublishSubject<Integer> subject = PublishSubject.create();
    Observable<Integer> limitedObservable = SubscriptionLimiter.limitSubscriptions(1, subject);
    TestSubscriber<Integer> subscriber = new TestSubscriber<>();
    TestSubscriber<Integer> subscriber2 = new TestSubscriber<>();
    limitedObservable.subscribe(subscriber);
    // when
    limitedObservable.subscribe(subscriber2);
    subject.onNext(123);
    // then
    assertThat(subscriber2.getOnNextEvents()).isEmpty();
    assertThat(subscriber2.getOnErrorEvents()).hasSize(1);

}
 
Example 8
Source File: ListStoreAppsPresenterTest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Test public void loadAppsAfterRefreshWithLoadingError() {
  //Given an initialized ListStoreAppsPresenter with a STORE_ID and a limit of apps
  //When onCreate lifecycle call event happens
  //and the view is refreshed by the user
  //and the app model is processing another request
  PublishSubject<Void> refreshEvent = PublishSubject.create();
  when(view.getRefreshEvent()).thenReturn(refreshEvent);

  when(appCenter.loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST)).thenReturn(
      Single.just(appsModelLoading));

  listStoreAppsPresenter.present();
  lifecycleEvent.onNext(View.LifecycleEvent.CREATE);
  refreshEvent.onNext(null);

  //Then when new apps are requested
  verify(appCenter).loadFreshApps(STORE_ID_TEST, LIMIT_APPS_TEST);
  //and apps model is loading
  //hide loading
  verify(view).hideRefreshLoading();
  //and do nothing else
  verify(view, never()).setApps(appsModelLoading.getList());
  verify(view, never()).showGenericError();
  verify(view, never()).showNetworkError();
}
 
Example 9
Source File: GeneralPreference.java    From rx-shared-preferences with Apache License 2.0 5 votes vote down vote up
public GeneralPreference(SharedPreferences sharedPreferences) {
  if (sharedPreferences == null) {
    throw new RuntimeException("SharedPreferences can not be null");
  }
  mSharedPreferences = sharedPreferences;
  mSubject = PublishSubject.create();
  mCaches = new ConcurrentHashMap<>();
  mConverters = new HashMap<>();
}
 
Example 10
Source File: EditorialPresenterTest.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
@Before public void setupEditorialPresenter() {
  MockitoAnnotations.initMocks(this);
  presenter = new EditorialPresenter(view, editorialManager, Schedulers.immediate(), crashReport,
      permissionManager, permissionService, editorialAnalytics, editorialNavigator,
      userFeedbackAnalytics, moPubAdsManager);
  lifecycleEvent = PublishSubject.create();
  reactionButtonClickEvent = PublishSubject.create();
  reactionButtonLongPressEvent = PublishSubject.create();
  reactionClickEvent = PublishSubject.create();
  snackLoginEvent = PublishSubject.create();
  editorialContent = new ArrayList<>();
  editorialContent.add(
      new EditorialContent("title", Collections.emptyList(), "message", "type", 1, "appName",
          "icon", 1, "packageName", 0, "graphic", null, 1, "storeName", "verName", 0, "path",
          "pathAlt", "md5", 0, Collections.emptyList(), Collections.emptyList(), false, null));
  editorialViewModel = new EditorialViewModel(editorialContent, "title", "caption", "background",
      Collections.emptyList(), editorialContent, false, "1", "CURATION_1", "");
  downloadModel = new EditorialDownloadModel(DownloadModel.Action.INSTALL, 0,
      DownloadModel.DownloadState.ACTIVE, 1);
  errorEditorialViewModel = new EditorialViewModel(EditorialViewModel.Error.GENERIC);
  loadingEditorialViewModel = new EditorialViewModel(true);
  when(view.getLifecycleEvent()).thenReturn(lifecycleEvent);
  when(view.reactionsButtonClicked()).thenReturn(reactionButtonClickEvent);
  when(view.reactionsButtonLongPressed()).thenReturn(reactionButtonLongPressEvent);
  when(view.reactionClicked()).thenReturn(reactionClickEvent);
  when(view.snackLoginClick()).thenReturn(snackLoginEvent);
}
 
Example 11
Source File: SubscriptionLimiterTest.java    From MarketData with Apache License 2.0 5 votes vote down vote up
@Test
public void should_allow_one_subscription() {
    // given
    PublishSubject<Integer> subject = PublishSubject.create();
    Observable<Integer> limitedObservable = SubscriptionLimiter.limitSubscriptions(1, subject);
    TestSubscriber<Integer> subscriber = new TestSubscriber<>();
    // when
    limitedObservable.subscribe(subscriber);
    subject.onNext(123);
    // then
    assertThat(subscriber.getOnNextEvents()).hasSize(1).contains(123);
}
 
Example 12
Source File: DeliverFirstTest.java    From nucleus with MIT License 4 votes vote down vote up
@Test(expected = OnErrorNotImplementedException.class)
    public void testThrowDuringOnNext() throws Exception {

//        Observable
//            .just(1)
//            .filter(new Func1<Integer, Boolean>() {
//                @Override
//                public Boolean call(Integer integer) {
//                    return true;
//                }
//            })
//            .first()
//            .subscribe(new Action1<Integer>() {
//                @Override
//                public void call(Integer integer) {
//                    throw new RuntimeException();
//                }
//            });

        PublishSubject<Object> view = PublishSubject.create();

        final PublishSubject<Integer> subject = PublishSubject.create();
        new DeliverFirst<Object, Integer>(view)
            .call(subject)
            .subscribe(new Action1<Delivery<Object, Integer>>() {
                @Override
                public void call(Delivery<Object, Integer> delivery) {
                    delivery.split(
                        new Action2<Object, Integer>() {
                            @Override
                            public void call(Object o, Integer integer) {
                                throw new RuntimeException();
                            }
                        },
                        null
                    );
                }
            });

        subject.onNext(3);
        view.onNext(100);
    }
 
Example 13
Source File: States.java    From RHub with Apache License 2.0 4 votes vote down vote up
@Setup(Level.Iteration)
public void setup() {
    ps = PublishSubject.create();
    upstream = Observable.range(0, count).publish();
    upstream.subscribe(ps);
}
 
Example 14
Source File: RxGoogleAuth.java    From RxSocialAuth with Apache License 2.0 4 votes vote down vote up
/**
 * Google silent sign in by launching a GoogleAuthHiddenActivity
 *
 * @return a PublishSubject<RxAccount>
 */
public PublishSubject<RxAccount> silentSignIn(Credential credential) {
    mAccountSubject = PublishSubject.create();
    mRxGoogleAuthFragment.signIn(mAccountSubject, credential);
    return mAccountSubject;
}
 
Example 15
Source File: DefaultLoadBalancerServiceTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void movedTaskOnlyTargetAssociatedWithLoadBalancer() {
    String taskId = UUID.randomUUID().toString();
    String sourceJobId = UUID.randomUUID().toString();
    String targetJobId = UUID.randomUUID().toString();
    String targetLoadBalancerId = "lb-" + UUID.randomUUID().toString();
    PublishSubject<JobManagerEvent<?>> taskEvents = PublishSubject.create();

    when(client.registerAll(any(), any())).thenReturn(Completable.complete());
    when(client.deregisterAll(any(), any())).thenReturn(Completable.complete());
    when(v3JobOperations.observeJobs()).thenReturn(taskEvents);
    LoadBalancerTests.applyValidGetJobMock(v3JobOperations, sourceJobId);
    LoadBalancerTests.applyValidGetJobMock(v3JobOperations, targetJobId);

    LoadBalancerConfiguration configuration = LoadBalancerTests.mockConfiguration(MIN_TIME_IN_QUEUE_MS);
    DefaultLoadBalancerService service = new DefaultLoadBalancerService(
            runtime, configuration, client, loadBalancerStore, loadBalancerJobOperations, reconciler, validator, testScheduler);

    AssertableSubscriber<Batch<TargetStateBatchable, String>> testSubscriber = service.events().test();

    assertThat(service.getJobLoadBalancers(sourceJobId).toBlocking().toIterable()).isEmpty();

    assertTrue(service.addLoadBalancer(targetJobId, targetLoadBalancerId).await(100, TimeUnit.MILLISECONDS));
    assertThat(service.getJobLoadBalancers(targetJobId).toBlocking().toIterable())
            .containsExactlyInAnyOrder(targetLoadBalancerId);

    testScheduler.advanceTimeBy(FLUSH_WAIT_TIME_MS, TimeUnit.MILLISECONDS);

    testSubscriber.assertNoErrors().assertValueCount(0);
    verify(client, never()).registerAll(any(), any());
    verify(client, never()).deregisterAll(any(), any());
    verifyNoReconcilerIgnore();

    Task moved = ServiceJobTask.newBuilder()
            .withJobId(targetJobId)
            .withId(taskId)
            .withStatus(TaskStatus.newBuilder().withState(TaskState.Started).build())
            .withTaskContext(CollectionsExt.asMap(
                    TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP, "1.2.3.4",
                    TaskAttributes.TASK_ATTRIBUTES_MOVED_FROM_JOB, sourceJobId
            )).build();

    // detect the task is moved and gets registered on the target
    taskEvents.onNext(TaskUpdateEvent.newTaskFromAnotherJob(null, moved, callMetadata));
    testScheduler.advanceTimeBy(FLUSH_WAIT_TIME_MS, TimeUnit.MILLISECONDS);

    testSubscriber.assertNoErrors().assertValueCount(1);
    verify(client).registerAll(eq(targetLoadBalancerId), argThat(set -> set.contains("1.2.3.4")));
    verify(client, never()).deregisterAll(any(), any());
    verifyReconcilerIgnore(targetLoadBalancerId, "1.2.3.4");
}
 
Example 16
Source File: RxBus.java    From AppPlus with MIT License 4 votes vote down vote up
private RxBus(){
    rxBus = new SerializedSubject(PublishSubject.<T>create());
}
 
Example 17
Source File: DefaultLoadBalancerServiceTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void multipleLoadBalancersPerJob() {
    PublishSubject<JobManagerEvent<?>> taskEvents = PublishSubject.create();
    String jobId = UUID.randomUUID().toString();
    String firstLoadBalancerId = "lb-" + UUID.randomUUID().toString();
    String secondLoadBalancerId = "lb-" + UUID.randomUUID().toString();
    int numberOfStartedTasks = 5;

    when(client.registerAll(any(), any())).thenReturn(Completable.complete());
    when(client.deregisterAll(any(), any())).thenReturn(Completable.complete());
    when(v3JobOperations.observeJobs()).thenReturn(taskEvents);
    LoadBalancerTests.applyValidGetJobMock(v3JobOperations, jobId);
    List<Task> tasks = LoadBalancerTests.buildTasksStarted(numberOfStartedTasks, jobId);
    Collection<LoadBalancerTargetState> firstExpectedTargets = tasks.stream()
            .map(task -> new LoadBalancerTargetState(
                    new LoadBalancerTarget(firstLoadBalancerId, task.getId(), task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP)),
                    REGISTERED
            ))
            .collect(Collectors.toList());
    Collection<LoadBalancerTargetState> secondExpectedTargets = tasks.stream()
            .map(task -> new LoadBalancerTargetState(
                    new LoadBalancerTarget(secondLoadBalancerId, task.getId(), task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP)),
                    REGISTERED
            ))
            .collect(Collectors.toList());

    when(v3JobOperations.getTasks(jobId)).thenReturn(CollectionsExt.merge(
            tasks,
            LoadBalancerTests.buildTasks(2, jobId, TaskState.StartInitiated),
            LoadBalancerTests.buildTasks(2, jobId, TaskState.KillInitiated),
            LoadBalancerTests.buildTasks(3, jobId, TaskState.Finished),
            LoadBalancerTests.buildTasks(1, jobId, TaskState.Disconnected)
    ));

    LoadBalancerConfiguration configuration = LoadBalancerTests.mockConfiguration(MIN_TIME_IN_QUEUE_MS);
    DefaultLoadBalancerService service = new DefaultLoadBalancerService(
            runtime, configuration, client, loadBalancerStore, loadBalancerJobOperations, reconciler, validator, testScheduler);

    AssertableSubscriber<Batch<TargetStateBatchable, String>> testSubscriber = service.events().test();

    // associate two load balancers to the same job

    assertTrue(service.addLoadBalancer(jobId, firstLoadBalancerId).await(100, TimeUnit.MILLISECONDS));
    assertTrue(service.addLoadBalancer(jobId, secondLoadBalancerId).await(100, TimeUnit.MILLISECONDS));
    assertThat(service.getJobLoadBalancers(jobId).toList().toBlocking().single())
            .containsOnly(firstLoadBalancerId, secondLoadBalancerId);
    verify(v3JobOperations, times(2)).getTasks(jobId);

    testScheduler.advanceTimeBy(FLUSH_WAIT_TIME_MS, TimeUnit.MILLISECONDS);

    // 1 batch per loadbalancer
    testSubscriber.assertNoErrors().assertValueCount(2);
    assertThat(loadBalancerStore.getLoadBalancerTargets(firstLoadBalancerId).collectList().block())
            .containsExactlyInAnyOrderElementsOf(firstExpectedTargets);
    assertThat(loadBalancerStore.getLoadBalancerTargets(secondLoadBalancerId).collectList().block())
            .containsExactlyInAnyOrderElementsOf(secondExpectedTargets);
    verify(client).registerAll(eq(firstLoadBalancerId), argThat(targets -> targets != null && targets.size() == numberOfStartedTasks));
    verify(client).registerAll(eq(secondLoadBalancerId), argThat(targets -> targets != null && targets.size() == numberOfStartedTasks));
    verify(client, never()).deregisterAll(eq(firstLoadBalancerId), any());
    verify(client, never()).deregisterAll(eq(secondLoadBalancerId), any());
    verifyReconcilerIgnore(firstLoadBalancerId, LoadBalancerTests.ipAddresses(tasks));
    verifyReconcilerIgnore(secondLoadBalancerId, LoadBalancerTests.ipAddresses(tasks));

    // now some more tasks are added to the job, check if both load balancers get updated

    List<Task> newTasks = new ArrayList<>();
    for (int i = 1; i <= numberOfStartedTasks; i++) {
        String taskId = UUID.randomUUID().toString();
        Task startingWithIp = ServiceJobTask.newBuilder()
                .withJobId(jobId)
                .withId(taskId)
                .withStatus(TaskStatus.newBuilder().withState(TaskState.StartInitiated).build())
                .withTaskContext(CollectionsExt.asMap(
                        TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP, String.format("%1$d.%1$d.%1$d.%1$d", i + numberOfStartedTasks)
                )).build();
        Task started = startingWithIp.toBuilder()
                .withStatus(TaskStatus.newBuilder().withState(TaskState.Started).build())
                .build();
        newTasks.add(started);

        taskEvents.onNext(TaskUpdateEvent.taskChange(null, started, startingWithIp, callMetadata));
    }

    testScheduler.advanceTimeBy(FLUSH_WAIT_TIME_MS, TimeUnit.MILLISECONDS);

    // 2 more batches (one per load balancer)
    testSubscriber.assertNoErrors().assertValueCount(4);
    verify(client, times(2)).registerAll(eq(firstLoadBalancerId), argThat(targets -> targets != null && targets.size() == numberOfStartedTasks));
    verify(client, times(2)).registerAll(eq(secondLoadBalancerId), argThat(targets -> targets != null && targets.size() == numberOfStartedTasks));
    verify(client, never()).deregisterAll(eq(firstLoadBalancerId), any());
    verify(client, never()).deregisterAll(eq(secondLoadBalancerId), any());
    verifyReconcilerIgnore(firstLoadBalancerId, LoadBalancerTests.ipAddresses(newTasks));
    verifyReconcilerIgnore(secondLoadBalancerId, LoadBalancerTests.ipAddresses(newTasks));
    assertThat(loadBalancerStore.getLoadBalancerTargets(firstLoadBalancerId).collectList().block())
            .hasSize(firstExpectedTargets.size() + numberOfStartedTasks);
    assertThat(loadBalancerStore.getLoadBalancerTargets(secondLoadBalancerId).collectList().block())
            .hasSize(secondExpectedTargets.size() + numberOfStartedTasks);
}
 
Example 18
Source File: RxBus.java    From HeroVideo-master with Apache License 2.0 4 votes vote down vote up
private RxBus()
{

    bus = new SerializedSubject<>(PublishSubject.create());
}
 
Example 19
Source File: AppsFragment.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getFragmentComponent(savedInstanceState).inject(this);
  appcUpgradesSectionLoaded = PublishSubject.create();
}
 
Example 20
Source File: RxSmartLockPasswords.java    From RxSocialAuth with Apache License 2.0 2 votes vote down vote up
/**
 * Save credential
 *
 * @param credential the credential
 * @return a PublishSubject<RxStatus>
 */
public PublishSubject<RxStatus> saveCredential(Credential credential) {
    mStatusSubject = PublishSubject.create();
    mRxSmartLockPasswordsFragment.saveCredential(mStatusSubject, credential, null);
    return mStatusSubject;
}