Java Code Examples for io.reactivex.subjects.BehaviorSubject#createDefault()

The following examples show how to use io.reactivex.subjects.BehaviorSubject#createDefault() . 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: 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 2
Source File: RxCmdShellTest.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@Test
public void testClose_waitForCommands() {
    BehaviorSubject<Boolean> idler = BehaviorSubject.createDefault(false);
    when(cmdProcessor.isIdle()).thenReturn(idler);

    RxCmdShell shell = new RxCmdShell(builder, rxShell);
    shell.open().test().awaitDone(1, TimeUnit.SECONDS).assertNoTimeout().values().get(0);
    shell.isAlive().test().awaitDone(1, TimeUnit.SECONDS).assertNoTimeout().assertValue(true);

    shell.close().test().awaitDone(1, TimeUnit.SECONDS).assertTimeout();

    idler.onNext(true);

    shell.close().test().awaitDone(1, TimeUnit.SECONDS).assertNoTimeout().assertValue(0);

    verify(cmdProcessor).isIdle();
    verify(rxShellSession).close();
}
 
Example 3
Source File: RecyclerViewAdapterTest.java    From android-mvvm with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    List<ViewModel> vms = TestViewModel.dummyViewModels(INITIAL_COUNT);

    viewModelsSource = BehaviorSubject.createDefault(vms);
    testViewProvider = new TestViewProvider();
    testBinder = new TestViewModelBinder();
    subscriptionCounter = new SubscriptionCounter<>();
    sut = new RecyclerViewAdapter(viewModelsSource.compose(subscriptionCounter),
            testViewProvider, testBinder);

    notifyCallCount = 0;
    defaultObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            notifyCallCount++;
        }
    };
    sut.registerAdapterDataObserver(defaultObserver);
}
 
Example 4
Source File: EventCapturePresenterImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public EventCapturePresenterImpl(EventCaptureContract.View view, String eventUid,
                                 EventCaptureContract.EventCaptureRepository eventCaptureRepository,
                                 RulesUtilsProvider rulesUtils,
                                 ValueStore valueStore, SchedulerProvider schedulerProvider) {
    this.view = view;
    this.eventUid = eventUid;
    this.eventCaptureRepository = eventCaptureRepository;
    this.rulesUtils = rulesUtils;
    this.valueStore = valueStore;
    this.schedulerProvider = schedulerProvider;
    this.currentPosition = 0;
    this.sectionsToHide = new ArrayList<>();
    this.currentSection = new ObservableField<>("");
    this.errors = new HashMap<>();
    this.emptyMandatoryFields = new HashMap<>();
    this.canComplete = true;
    this.sectionList = new ArrayList<>();
    this.compositeDisposable = new CompositeDisposable();

    currentSectionPosition = PublishProcessor.create();
    sectionProcessor = PublishProcessor.create();
    showCalculationProcessor = PublishProcessor.create();
    progressProcessor = PublishProcessor.create();
    sectionAdjustProcessor = PublishProcessor.create();
    formAdjustProcessor = PublishProcessor.create();
    notesCounterProcessor = PublishProcessor.create();
    formFieldsProcessor = BehaviorSubject.createDefault(new ArrayList<>());
}
 
Example 5
Source File: MviBasePresenter.java    From mosby with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Presenter with the initial view state
 *
 * @param initialViewState initial view state (must be not null)
 */
public MviBasePresenter(@NonNull VS initialViewState) {
    if (initialViewState == null) {
        throw new NullPointerException("Initial ViewState == null");
    }

    viewStateBehaviorSubject = BehaviorSubject.createDefault(initialViewState);
    reset();
}
 
Example 6
Source File: BehaviorWithLatestTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void secondInit() {
    BehaviorSubject<String> s1 = BehaviorSubject.create();
    BehaviorSubject<String> s2 = BehaviorSubject.createDefault("");

    TestObserver<Boolean> to = s1.withLatestFrom(s2, (a, b) -> true)
    .test();

    to.assertEmpty();

    s1.onNext("");

    to.assertValue(true);
}
 
Example 7
Source File: BehaviorWithLatestTest.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Test
public void bothInit() {
    BehaviorSubject<String> s1 = BehaviorSubject.createDefault("");
    BehaviorSubject<String> s2 = BehaviorSubject.createDefault("");
    
    s1.withLatestFrom(s2, (a, b) -> true)
    .test()
    .assertValue(true);
}
 
Example 8
Source File: ReadOnlyFieldTests.java    From android-mvvm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    sourceSubject = BehaviorSubject.createDefault(INITIAL_VALUE);
    subscriptionCounter = new SubscriptionCounter<>();
    Observable<Integer> source = sourceSubject.compose(subscriptionCounter);
    sut = ReadOnlyField.create(source);
}
 
Example 9
Source File: ViewPagerAdapterTest.java    From android-mvvm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    viewModelsSource = BehaviorSubject.createDefault(TestViewModel.dummyViewModels(INITIAL_COUNT));
    testViewProvider = new TestViewProvider();
    testBinder = new TestViewModelBinder();
    subscriptionCounter = new SubscriptionCounter<>();
    sut = new TestViewPagerAdapter(viewModelsSource.compose(subscriptionCounter),
            testViewProvider, testBinder);

    connection = sut.connect();
}
 
Example 10
Source File: AbstractAccountsProvider.java    From science-journal with Apache License 2.0 5 votes vote down vote up
public AbstractAccountsProvider(Context context) {
  applicationContext = context.getApplicationContext();
  usageTracker = WhistlePunkApplication.getUsageTracker(applicationContext);
  NonSignedInAccount nonSignedInAccount = NonSignedInAccount.getInstance(applicationContext);
  addAccount(nonSignedInAccount);
  currentAccount = nonSignedInAccount;
  observableCurrentAccount = BehaviorSubject.createDefault(nonSignedInAccount);
}
 
Example 11
Source File: GoogleAccount.java    From science-journal with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new GoogleAccount instance.
 */

GoogleAccount(Context context, @Nullable Account account, GoogleSignInAccount googleSignInAccount) {
  super(context);
  accountSubject =
      (account != null) ? BehaviorSubject.createDefault(account) : BehaviorSubject.create();
  this.googleSignInAccount = googleSignInAccount;
  this.account = googleSignInAccount.getAccount();
  setAccount(account);
  this.accountKey = AccountsUtils.makeAccountKey(NAMESPACE, this.googleSignInAccount.getId());
}
 
Example 12
Source File: RxCmdShellTest.java    From RxShell with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    super.setup();
    when(builder.getProcessorFactory()).thenReturn(commandProcessorFactory);
    when(commandProcessorFactory.create()).thenReturn(cmdProcessor);
    BehaviorSubject<Boolean> idlePub = BehaviorSubject.createDefault(true);
    when(cmdProcessor.isIdle()).thenReturn(idlePub);

    when(rxShell.open()).thenReturn(Single.create(emitter -> {
        when(rxShellSession.waitFor()).thenReturn(Single.create(e -> waitForEmitter = e));
        emitter.onSuccess(rxShellSession);
    }));

    when(rxShellSession.waitFor()).thenReturn(Single.just(0));
    when(rxShellSession.isAlive()).thenReturn(Single.just(true));
    when(rxShellSession.cancel()).thenReturn(Completable.create(e -> {
        when(rxShellSession.isAlive()).thenReturn(Single.just(false));
        waitForEmitter.onSuccess(1);
        idlePub.onNext(true);
        idlePub.onComplete();
        e.onComplete();
    }));
    when(rxShellSession.close()).thenReturn(Single.create(e -> {
        when(rxShellSession.isAlive()).thenReturn(Single.just(false));
        waitForEmitter.onSuccess(0);
        e.onSuccess(0);
        idlePub.onNext(true);
        idlePub.onComplete();
    }));
}
 
Example 13
Source File: RpcRx.java    From api with Apache License 2.0 5 votes vote down vote up
/**
 * @param rpc An API provider using HTTP or WebSocket
 */
public RpcRx(RpcCore rpc) {
    this.api = rpc;
    this.eventEmitter = new EventEmitter();
    this.isConnected = BehaviorSubject.createDefault(this.api.getProvider().isConnected());

    this.initEmitters(this.api.getProvider());

    this.author = this.createInterface(this.api.author());
    this.chain = this.createInterface(this.api.chain());
    this.state = this.createInterface(this.api.state());
    this.system = this.createInterface(this.api.system());
}
 
Example 14
Source File: StompClient.java    From StompProtocolAndroid with MIT License 4 votes vote down vote up
synchronized private BehaviorSubject<Boolean> getConnectionStream() {
    if (connectionStream == null || connectionStream.hasComplete()) {
        connectionStream = BehaviorSubject.createDefault(false);
    }
    return connectionStream;
}
 
Example 15
Source File: BehaviorWithLatestTest.java    From akarnokd-misc with Apache License 2.0 4 votes vote down vote up
@Test
public void firstInit() {
    BehaviorSubject<String> s1 = BehaviorSubject.createDefault("");
    BehaviorSubject<String> s2 = BehaviorSubject.create();

    TestObserver<Boolean> to = s1.withLatestFrom(s2, (a, b) -> true)
    .test();

    to.assertEmpty();

    s2.onNext("");

    to.assertEmpty();

    s1.onNext("");

    to.assertValue(true);
}
 
Example 16
Source File: BehaviorSubjectCombineLatest.java    From akarnokd-misc with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    subject1 = BehaviorSubject.createDefault("hello");
    subject2 = BehaviorSubject.createDefault("goodbye");
    
    subject1.subscribe(v -> System.out.println("Subject1 it1: " + v));
    
    click();
    
    Thread.sleep(1);

    click();
    
    Thread.sleep(1);

    click();
}
 
Example 17
Source File: SyncAdapter.java    From moVirt with Apache License 2.0 4 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient providerClient, SyncResult syncResult) {
    try {
        final MovirtAccount movirtAccount = accountManagerHelper.asMoAccount(account);
        final AccountEnvironment environment = environmentStore.getEnvironment(movirtAccount);

        if (environment.isLoginInProgress()) {
            // sync will be called again if the login succeeds
            return;
        }
        // onPerformSync calls are guaranteed to be serialized for the same account
        // so progress is atomic
        setSyncInProgress(movirtAccount, true);

        // remember last used sync action, because we may try it again if it fails
        final Subject<SyncAction> syncActions = BehaviorSubject.createDefault(SyncAction.getFirstAction());
        final Observable<LoginStatus> loginStatus = rxStore.isLoginInProgressObservable(movirtAccount)
                .observeOn(Schedulers.newThread());

        Observable.combineLatest(syncActions, loginStatus, SyncBundle::new)
                .doOnNext(syncBundle -> { // sync
                    if (syncBundle.action == SyncAction.EVENT
                            && !environment.getSharedPreferencesHelper().isPollEventsEnabled()) {
                        return;
                    }
                    environment.getFacade(syncBundle.action.getClazz()).syncAllUnsafe();
                })
                .retryWhen(errors ->
                        // run again with another MAX_SYNC_ERRORS tries; + 1 is for signaling the last error
                        errors.zipWith(Observable.range(1, MAX_SYNC_ERRORS + 1), Pair::new)
                                .flatMap(err -> {
                                    if (err.second == MAX_SYNC_ERRORS + 1 // last try failed
                                            // or unrecoverable exception
                                            || ((err.first instanceof RestCallException) && !((RestCallException) err.first).isRepeatable())) {
                                        return Observable.<Long>error(err.first); // cancel the sync
                                    }
                                    // wait few seconds before trying again
                                    Log.d(TAG, String.format("Account %s: failed sync. Retrying...", movirtAccount.getName()));
                                    return Observable.timer(WAIT_BEFORE_NEXT_TRY, TimeUnit.SECONDS);
                                }))
                .doFinally(() -> setSyncInProgress(movirtAccount, false))
                //  finish if there is no reason to continue syncing
                .takeWhile(SyncBundle::isNotFinished)
                // block onPerformSync method -> the sync status will be atomic
                .blockingSubscribe(syncBundle -> syncActions.onNext(syncBundle.action.getNextAction()), // continue sync with next action
                        throwable -> {
                            // android can interrupt us while we sleep, probably because the same sync is pending; so ignore this one
                            if (!(throwable instanceof InterruptedException)) {
                                // if not, first real error is handled (depends on MAX_SYNC_ERRORS)
                                environment.getRestErrorHandler().handleError(throwable, "Sync failed. ");
                            }
                        });
    } catch (AccountDeletedException | IllegalStateException ignore) {
    }
}