io.reactivex.processors.PublishProcessor Java Examples

The following examples show how to use io.reactivex.processors.PublishProcessor. 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: LiveDataReactiveStreamsTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsFromPublisherSubscribeWithDelay() {
    PublishProcessor<String> processor = PublishProcessor.create();
    processor.delaySubscription(100, TimeUnit.SECONDS, sBackgroundScheduler);
    LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);

    liveData.observe(mLifecycleOwner, mObserver);

    processor.onNext("foo");
    liveData.removeObserver(mObserver);
    sBackgroundScheduler.triggerActions();
    liveData.observe(mLifecycleOwner, mObserver);

    processor.onNext("bar");
    processor.onNext("baz");

    assertThat(mLiveDataOutput, is(Arrays.asList("foo", "foo", "bar", "baz")));
}
 
Example #2
Source File: FilterManager.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void reset() {
    ouFilters = new ArrayList<>();
    stateFilters = new ArrayList<>();
    periodFilters = null;
    catOptComboFilters = new ArrayList<>();
    eventStatusFilters = new ArrayList<>();
    assignedFilter = false;

    ouFiltersApplied = new ObservableField<>(0);
    stateFiltersApplied = new ObservableField<>(0);
    periodFiltersApplied = new ObservableField<>(0);
    catOptCombFiltersApplied = new ObservableField<>(0);
    eventStatusFiltersApplied = new ObservableField<>(0);
    assignedToMeApplied = new ObservableField<>(0);

    filterProcessor = PublishProcessor.create();
    ouTreeProcessor = PublishProcessor.create();
    periodRequestProcessor = PublishProcessor.create();
}
 
Example #3
Source File: SyncManagerPresenter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
SyncManagerPresenter(
        D2 d2,
        SchedulerProvider schedulerProvider,
        GatewayValidator gatewayValidator,
        PreferenceProvider preferenceProvider,
        WorkManagerController workManagerController,
        SettingsRepository settingsRepository,
        SyncManagerContracts.View view,
        AnalyticsHelper analyticsHelper) {
    this.view = view;
    this.d2 = d2;
    this.settingsRepository = settingsRepository;
    this.schedulerProvider = schedulerProvider;
    this.preferenceProvider = preferenceProvider;
    this.gatewayValidator = gatewayValidator;
    this.workManagerController = workManagerController;
    this.analyticsHelper = analyticsHelper;
    checkData = PublishProcessor.create();
    compositeDisposable = new CompositeDisposable();
}
 
Example #4
Source File: TeiDashboardPresenter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TeiDashboardPresenter(
        TeiDashboardContracts.View view,
        String teiUid, String programUid,
        DashboardRepository dashboardRepository,
        SchedulerProvider schedulerProvider,
        AnalyticsHelper analyticsHelper,
        PreferenceProvider preferenceProvider,
        FilterManager filterManager
) {
    this.view = view;
    this.teiUid = teiUid;
    this.programUid = programUid;
    this.analyticsHelper = analyticsHelper;
    this.dashboardRepository = dashboardRepository;
    this.schedulerProvider = schedulerProvider;
    this.preferenceProvider = preferenceProvider;
    this.filterManager = filterManager;
    compositeDisposable = new CompositeDisposable();
    notesCounterProcessor = PublishProcessor.create();
}
 
Example #5
Source File: FlatMapWithTwoErrors.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void innerCancelled() {
    PublishProcessor<Integer> pp1 = PublishProcessor.create();
    PublishProcessor<Integer> pp2 = PublishProcessor.create();
    
    pp1
    .flatMap(v -> pp2)
    .test();

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

    pp1.onError(new Exception());
    
    assertFalse("Has subscribers?", pp2.hasSubscribers());
}
 
Example #6
Source File: SearchTEPresenter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public SearchTEPresenter(SearchTEContractsModule.View view,
                         D2 d2,
                         SearchRepository searchRepository,
                         SchedulerProvider schedulerProvider,
                         AnalyticsHelper analyticsHelper,
                         @Nullable String initialProgram) {
    this.view = view;
    this.searchRepository = searchRepository;
    this.d2 = d2;
    this.schedulerProvider = schedulerProvider;
    this.analyticsHelper = analyticsHelper;
    compositeDisposable = new CompositeDisposable();
    queryData = new HashMap<>();
    queryProcessor = PublishProcessor.create();
    mapProcessor = PublishProcessor.create();
    enrollmentMapProcessor = PublishProcessor.create();
    selectedProgram = initialProgram != null ? d2.programModule().programs().uid(initialProgram).blockingGet() : null;
    currentProgram = BehaviorSubject.createDefault(initialProgram != null ? initialProgram : "");
}
 
Example #7
Source File: EventCaptureFormFragment.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    binding = DataBindingUtil.inflate(inflater, R.layout.section_selector_fragment, container, false);
    binding.setPresenter(activity.getPresenter());
    this.flowableProcessor = PublishProcessor.create();
    this.sectionProcessor = PublishProcessor.create();
    this.flowableOptions = PublishProcessor.create();

    binding.actionButton.setOnClickListener(view -> {
        presenter.onActionButtonClick();
    });

    presenter.init();

    return binding.getRoot();
}
 
Example #8
Source File: FlatMapWithTwoErrors.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void innerCancelled2() {
    PublishProcessor<Integer> pp1 = PublishProcessor.create();
    PublishProcessor<Integer> pp2 = PublishProcessor.create();
    
    pp1
    .concatMap(v -> pp2)
    .test();

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

    pp1.onError(new Exception());
    
    assertFalse("Has subscribers?", pp2.hasSubscribers());
}
 
Example #9
Source File: CmdProcessorTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommand_callback_sync() {
    processor.attach(session);

    int cnt = 100;
    List<EnvVar<TestObserver<Cmd.Result>, TestSubscriber<String>>> testSubscribers = new ArrayList<>();
    for (int j = 0; j < cnt; j++) {
        List<String> cmds = new ArrayList<>();
        for (int i = 0; i < 10; i++) cmds.add("echo " + i);
        cmds.add("echo " + j);

        PublishProcessor<String> outputListener = PublishProcessor.create();
        TestSubscriber<String> outputObserver = outputListener.doOnEach(stringNotification -> TestHelper.sleep(1)).test();
        final Cmd cmd = Cmd.builder(cmds).outputProcessor(outputListener).build();
        final TestObserver<Cmd.Result> resultObserver = processor.submit(cmd).subscribeOn(Schedulers.newThread()).test();
        testSubscribers.add(new EnvVar<>(resultObserver, outputObserver));
    }
    for (EnvVar<TestObserver<Cmd.Result>, TestSubscriber<String>> envVar : testSubscribers) {
        envVar.first.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout().assertComplete();
        envVar.second.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout().assertValueCount(11);
    }
}
 
Example #10
Source File: PollingBlockchainSubscriptionStrategyTest.java    From eventeum with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    this.mockWeb3j = mock(Web3j.class);

    mockEthBlock = mock(EthBlock.class);
    mockEventStoreService = mock(EventStoreService.class);
    final EthBlock.Block mockBlock = mock(EthBlock.Block.class);

    when(mockBlock.getNumber()).thenReturn(BLOCK_NUMBER);
    when(mockBlock.getHash()).thenReturn(BLOCK_HASH);
    when(mockBlock.getTimestamp()).thenReturn(BLOCK_TIMESTAMP);
    when(mockEthBlock.getBlock()).thenReturn(mockBlock);

    blockPublishProcessor = PublishProcessor.create();
    when(mockWeb3j.blockFlowable(true)).thenReturn(blockPublishProcessor);

    underTest = new PollingBlockSubscriptionStrategy(mockWeb3j,
            NODE_NAME, mockEventStoreService, new DummyAsyncTaskService());
}
 
Example #11
Source File: CmdBuilderTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilder_from() {
    Cmd orig = Cmd.builder(UUID.randomUUID().toString())
            .outputBuffer(false)
            .errorBuffer(false)
            .timeout(1337)
            .outputProcessor(PublishProcessor.create())
            .errorProcessor(PublishProcessor.create())
            .build();

    Cmd copy = Cmd.from(orig).build();
    assertEquals(orig.getCommands(), copy.getCommands());
    assertEquals(orig.isOutputBufferEnabled(), copy.isOutputBufferEnabled());
    assertEquals(orig.isErrorBufferEnabled(), copy.isErrorBufferEnabled());
    assertEquals(orig.getTimeout(), copy.getTimeout());
    assertEquals(orig.getOutputProcessor(), copy.getOutputProcessor());
    assertEquals(orig.getErrorProcessor(), copy.getErrorProcessor());
}
 
Example #12
Source File: DoubleBindingTextViewFragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(
    LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  View layout = inflater.inflate(R.layout.fragment_double_binding_textview, container, false);
  unbinder = ButterKnife.bind(this, layout);

  _resultEmitterSubject = PublishProcessor.create();

  _disposable =
      _resultEmitterSubject.subscribe(
          aFloat -> {
            _result.setText(String.valueOf(aFloat));
          });

  onNumberChanged();
  _number2.requestFocus();

  return layout;
}
 
Example #13
Source File: NetworkDetectorFragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
  super.onStart();

  publishProcessor = PublishProcessor.create();

  disposable =
      publishProcessor
          .startWith(getConnectivityStatus(getActivity()))
          .distinctUntilChanged()
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              online -> {
                if (online) {
                  log("You are online");
                } else {
                  log("You are offline");
                }
              });

  listenToNetworkConnectivity();
}
 
Example #14
Source File: CmdBuilderTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuild() {
    final PublishProcessor<String> outputPub = PublishProcessor.create();
    final PublishProcessor<String> errorPub = PublishProcessor.create();
    Cmd cmd = Cmd.builder("cmd1")
            .outputBuffer(false)
            .errorBuffer(false)
            .timeout(1337)
            .outputProcessor(outputPub)
            .errorProcessor(errorPub)
            .build();
    assertThat(cmd.getCommands(), contains("cmd1"));
    assertThat(cmd.getOutputProcessor(), is(outputPub));
    assertThat(cmd.getErrorProcessor(), is(errorPub));
    assertThat(cmd.getTimeout(), is(1337L));
    assertThat(cmd.isOutputBufferEnabled(), is(false));
    assertThat(cmd.isErrorBufferEnabled(), is(false));
}
 
Example #15
Source File: CmdBuilderTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_oneshot_exception_no_buffers() throws IOException {
    RxCmdShell shell = mock(RxCmdShell.class);
    Exception ex = new IOException("Error message");
    when(shell.open()).thenReturn(Single.error(ex));
    when(shell.isAlive()).thenReturn(Single.just(false));

    final PublishProcessor<String> errorPub = PublishProcessor.create();
    final TestSubscriber<String> errorSub = errorPub.test();
    final PublishProcessor<String> outputPub = PublishProcessor.create();
    final TestSubscriber<String> outputSub = outputPub.test();
    final Cmd.Result result = Cmd.builder("")
            .outputBuffer(false)
            .errorBuffer(false)
            .outputProcessor(outputPub)
            .errorProcessor(errorPub)
            .execute(shell);
    assertThat(result.getExitCode(), is(Cmd.ExitCode.EXCEPTION));
    assertThat(result.getErrors(), is(nullValue()));
    assertThat(result.getOutput(), is(nullValue()));
    assertThat(errorSub.valueCount(), is(1));
    assertThat(outputSub.valueCount(), is(0));
    errorSub.assertComplete();
    outputSub.assertComplete();
}
 
Example #16
Source File: LiveDataReactiveStreamsTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsFromPublisherWithMultipleObserversAfterInactive() {
    final List<String> output2 = new ArrayList<>();
    PublishProcessor<String> processor = PublishProcessor.create();
    LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);

    liveData.observe(mLifecycleOwner, mObserver);

    processor.onNext("foo");
    processor.onNext("bar");

    // The second observer should only get the newest value and any later values.
    liveData.observe(mLifecycleOwner, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            output2.add(s);
        }
    });

    liveData.removeObserver(mObserver);
    processor.onNext("baz");

    assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar")));
    assertThat(output2, is(Arrays.asList("bar", "baz")));
}
 
Example #17
Source File: CmdProcessorTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommand_callback_async() {
    processor.attach(session);

    int cnt = 100;
    List<EnvVar<TestObserver<Cmd.Result>, TestSubscriber<String>>> testSubscribers = new ArrayList<>();
    for (int j = 0; j < cnt; j++) {
        List<String> cmds = new ArrayList<>();
        for (int i = 0; i < 10; i++) cmds.add("echo " + i);
        cmds.add("echo " + j);

        PublishProcessor<String> outputListener = PublishProcessor.create();
        TestSubscriber<String> outputObserver = outputListener.observeOn(Schedulers.newThread()).doOnEach(stringNotification -> TestHelper.sleep(1)).test();
        final Cmd cmd = Cmd.builder(cmds).outputProcessor(outputListener).build();
        final TestObserver<Cmd.Result> resultObserver = processor.submit(cmd).subscribeOn(Schedulers.newThread()).test();
        testSubscribers.add(new EnvVar<>(resultObserver, outputObserver));
    }
    for (EnvVar<TestObserver<Cmd.Result>, TestSubscriber<String>> envVar : testSubscribers) {
        envVar.first.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout().assertComplete();
        envVar.second.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout().assertValueCount(11);
    }
}
 
Example #18
Source File: LiveDataReactiveStreamsTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsFromPublisherWithMultipleObservers() {
    final List<String> output2 = new ArrayList<>();
    PublishProcessor<String> processor = PublishProcessor.create();
    LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);

    liveData.observe(mLifecycleOwner, mObserver);

    processor.onNext("foo");
    processor.onNext("bar");

    // The second observer should only get the newest value and any later values.
    liveData.observe(mLifecycleOwner, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            output2.add(s);
        }
    });

    processor.onNext("baz");

    assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
    assertThat(output2, is(Arrays.asList("bar", "baz")));
}
 
Example #19
Source File: PaginationFragment.java    From RxJava-Android-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);

  _bus = ((MainActivity) getActivity()).getRxBusSingleton();

  LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
  layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
  _pagingList.setLayoutManager(layoutManager);

  _adapter = new PaginationAdapter(_bus);
  _pagingList.setAdapter(_adapter);

  _paginator = PublishProcessor.create();
}
 
Example #20
Source File: PaginationAutoFragment.java    From RxJava-Android-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);

  _bus = ((MainActivity) getActivity()).getRxBusSingleton();

  LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
  layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
  _pagingList.setLayoutManager(layoutManager);

  _adapter = new PaginationAutoAdapter(_bus);
  _pagingList.setAdapter(_adapter);

  _paginator = PublishProcessor.create();
}
 
Example #21
Source File: BufferWithConditionAndTime.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
TestScheduler scheduler = new TestScheduler();
PublishProcessor<String> pp = PublishProcessor.create();

Function<Flowable<String>, Flowable<List<String>>> f = o -> 
        o.buffer(o.filter(v -> v.contains("Start")), 
                v -> Flowable.merge(o.filter(w -> w.contains("End")), 
                        Flowable.timer(5, TimeUnit.MINUTES, scheduler))); 

pp.publish(f)
.subscribe(System.out::println);

pp.onNext("Start");
pp.onNext("A");
pp.onNext("B");
pp.onNext("End");

pp.onNext("Start");
pp.onNext("C");

scheduler.advanceTimeBy(5, TimeUnit.MINUTES);

pp.onNext("Start");
pp.onNext("D");
pp.onNext("End");
pp.onComplete();
    
}
 
Example #22
Source File: BufferStartEndTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    TestScheduler scheduler = new TestScheduler();
    PublishProcessor<String> pp = PublishProcessor.create();

    Function<Flowable<String>, Flowable<List<String>>> f = o -> 
            o.buffer(o.filter(v -> v.contains("Start")), 
                     v -> Flowable.merge(o.filter(w -> w.contains("Start")), 
                                         Flowable.timer(5, TimeUnit.MINUTES, scheduler))); 

    pp.publish(f)
    .doOnNext(v -> {
        int s = v.size();
        if (s > 1 && v.get(s - 1).contains("Start")) {
            v.remove(s - 1);
        }
    })
    .subscribe(System.out::println);

    pp.onNext("Start");
    pp.onNext("A");
    pp.onNext("B");
    pp.onNext("End");

    pp.onNext("Start");
    pp.onNext("C");

    scheduler.advanceTimeBy(5, TimeUnit.MINUTES);

    pp.onNext("Start");
    pp.onNext("D");
    pp.onNext("End");
    pp.onComplete();
}
 
Example #23
Source File: SequenceEqualsCancelTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void flowable() {
    PublishProcessor<Integer> pp1 = PublishProcessor.create();
    PublishProcessor<Integer> pp2 = PublishProcessor.create();

    Flowable.sequenceEqual(pp1, pp2)
    .test()
    .cancel();

    Assert.assertFalse(pp1.hasSubscribers());
    Assert.assertFalse(pp2.hasSubscribers());
}
 
Example #24
Source File: RotationPersist2WorkerFragment.java    From RxJava-Android-Samples with Apache License 2.0 5 votes vote down vote up
/** This method will only be called once when the retained Fragment is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  _intStream = PublishProcessor.create();
  _lifeCycleStream = PublishProcessor.create();

  // Retain this fragment across configuration changes.
  setRetainInstance(true);

  _intStream.takeUntil(_lifeCycleStream);

  Flowable.interval(1, TimeUnit.SECONDS).map(Long::intValue).take(20).subscribe(_intStream);
}
 
Example #25
Source File: RxBus.java    From CrazyDaily with Apache License 2.0 5 votes vote down vote up
public <T> Flowable<T> toFlowable(String tag, Class<T> eventType) {
    FlowableProcessor<Object> processor = processorMap.get(tag);
    if (processor == null) {
        processor = PublishProcessor.create().toSerialized();
        processorMap.put(tag, processor);
    }
    return processor.ofType(eventType);
}
 
Example #26
Source File: LiveDataReactiveStreamsTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void convertsFromPublisher() {
    PublishProcessor<String> processor = PublishProcessor.create();
    LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(processor);

    liveData.observe(mLifecycleOwner, mObserver);

    processor.onNext("foo");
    processor.onNext("bar");
    processor.onNext("baz");

    assertThat(mLiveDataOutput, is(Arrays.asList("foo", "bar", "baz")));
}
 
Example #27
Source File: RxBus.java    From CrazyDaily with Apache License 2.0 5 votes vote down vote up
public void post(String tag, Object event) {
    FlowableProcessor<Object> processor = processorMap.get(tag);
    if (processor == null) {
        processor = PublishProcessor.create().toSerialized();
        processorMap.put(tag, processor);
    }
    processor.onNext(event);
}
 
Example #28
Source File: HarvesterTest.java    From RxShell with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpstreamTerminated_output() {
    publisher.onComplete();
    OutputHarvester.Crop crop = publisher.compose(harvesterFactory.forOutput(publisher, cmd)).test().assertComplete().assertValueCount(1).values().get(0);
    assertThat(crop.isComplete, is(false));

    publisher = PublishProcessor.create();
    publisher.onError(new InterruptedException());
    crop = publisher.compose(harvesterFactory.forOutput(publisher, cmd)).test().assertComplete().assertValueCount(1).values().get(0);
    assertThat(crop.isComplete, is(false));
}
 
Example #29
Source File: MainActivity.java    From RxAndroid-Examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    resultPublisher = PublishProcessor.create();
    subscriber = resultPublisher.subscribe(aFloat -> {
        tvSum.setText("Sum = " + aFloat);
    });
    onNumberChanged();
}
 
Example #30
Source File: HarvesterTest.java    From RxShell with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpstreamTerminated_error() {
    publisher.onComplete();
    ErrorHarvester.Crop crop = publisher.compose(harvesterFactory.forError(publisher, cmd)).test().assertComplete().assertValueCount(1).values().get(0);
    assertThat(crop.isComplete, is(false));

    publisher = PublishProcessor.create();
    publisher.onError(new InterruptedException());
    crop = publisher.compose(harvesterFactory.forError(publisher, cmd)).test().assertComplete().assertValueCount(1).values().get(0);
    assertThat(crop.isComplete, is(false));
}