io.reactivex.subjects.BehaviorSubject Java Examples

The following examples show how to use io.reactivex.subjects.BehaviorSubject. 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: 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 #2
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Notification<?>> Flowable<T> subscribe(
        Request request, String unsubscribeMethod, Class<T> responseType) {
    // We can't use usual Observer since we can call "onError"
    // before first client is subscribed and we need to
    // preserve it
    BehaviorSubject<T> subject = BehaviorSubject.create();

    // We need to subscribe synchronously, since if we return
    // an Flowable to a client before we got a reply
    // a client can unsubscribe before we know a subscription
    // id and this can cause a race condition
    subscribeToEventsStream(request, subject, responseType);

    return subject.doOnDispose(() -> closeSubscription(subject, unsubscribeMethod))
            .toFlowable(BackpressureStrategy.BUFFER);
}
 
Example #3
Source File: WebSocketService.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Notification<?>> Flowable<T> subscribe(
        Request request, String unsubscribeMethod, Class<T> responseType) {
    // We can't use usual Observer since we can call "onError"
    // before first client is subscribed and we need to
    // preserve it
    BehaviorSubject<T> subject = BehaviorSubject.create();

    // We need to subscribe synchronously, since if we return
    // an Flowable to a client before we got a reply
    // a client can unsubscribe before we know a subscription
    // id and this can cause a race condition
    subscribeToEventsStream(request, subject, responseType);

    return subject.doOnDispose(() -> closeSubscription(subject, unsubscribeMethod))
            .toFlowable(BackpressureStrategy.BUFFER);
}
 
Example #4
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 #5
Source File: CorePeripheral.java    From RxCentralBle with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<ConnectableState> connect() {
  if (sharedConnectionState != null) {
    return sharedConnectionState;
  }

  connectionStateSubject = BehaviorSubject.create();

  sharedConnectionState =
      connectionStateSubject
          .doOnNext(state -> connectedRelay.accept(state == CONNECTED))
          .doOnSubscribe(disposable -> processConnect())
          .doFinally(() -> disconnect())
          .replay(1)
          .refCount(); // Don't do this on normal disconnect status 0 / 8

  return sharedConnectionState;
}
 
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: ReplayRefCountSubjectTest.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    BehaviorSubject<Integer> subject = BehaviorSubject.create();

    Observable<Integer> observable = subject
            .doOnNext(e -> { 
                System.out.println("This emits for second subscriber"); 
            })
            .doOnSubscribe(s -> System.out.println("OnSubscribe"))
            .doOnDispose(() -> System.out.println("OnDispose"))
            .replay(1)
            .refCount()
            .doOnNext(e -> { System.out.println("This does NOT emit for second subscriber"); });

    System.out.println("Subscribe-1");
    // This line causes the test to fail.
    observable.takeUntil(Observable.just(1)).test();

    subject.onNext(2);

    System.out.println("Subscribe-2");
    TestObserver<Integer> subscriber = observable.take(1).test();
    Assert.assertTrue(subscriber.awaitTerminalEvent(2, TimeUnit.SECONDS));
}
 
Example #8
Source File: RxSearch.java    From incubator-taverna-mobile with Apache License 2.0 6 votes vote down vote up
public static Observable<String> fromSearchView(@NonNull final SearchView searchView) {
    final BehaviorSubject<String> subject = BehaviorSubject.create();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            subject.onNext(query);
            subject.onComplete();
            searchView.clearFocus();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            subject.onNext(newText);
            return true;
        }
    });

    return subject;
}
 
Example #9
Source File: LocationManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Inject
public LocationManager(
    Application app,
    PermissionsManager permissionsManager,
    SettingsManager settingsManager,
    RxFusedLocationProviderClient locationClient) {
  this.permissionsManager = permissionsManager;
  this.settingsManager = settingsManager;
  this.locationClient = locationClient;
  this.locationUpdates = BehaviorSubject.create();
  this.locationUpdateCallback = RxLocationCallback.create(locationUpdates);
}
 
Example #10
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> String getSubscriptionId(BehaviorSubject<T> subject) {
    return subscriptionForId
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue().getSubject() == subject)
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null);
}
 
Example #11
Source File: RunnerRoundProcessor.java    From 2018-TowerDefence with MIT License 5 votes vote down vote up
boolean processRound(BehaviorSubject<String> addToConsoleOutput) throws Exception {
    if (roundProcessed) {
        throw new InvalidOperationException("This round has already been processed!");
    }
    boolean processed = gameRoundProcessor.processRound(gameMap, commandsToProcess);

    ArrayList<String> errorList = gameRoundProcessor.getErrorList();
    String errorListText = "Error List: " + Arrays.toString(errorList.toArray());
    addToConsoleOutput.onNext(errorListText);

    roundProcessed = true;

    return processed;
}
 
Example #12
Source File: GameEngineRunner.java    From 2018-TowerDefence with MIT License 5 votes vote down vote up
public GameEngineRunner() {
    this.unsubscribe = BehaviorSubject.create();
    this.addToConsoleOutput = BehaviorSubject.create();
    this.addToConsoleOutput
            .takeUntil(this.unsubscribe)
            .subscribe(text -> consoleOutput += text);
}
 
Example #13
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void processSubscriptionResponse(
        EthSubscribe subscriptionReply, BehaviorSubject<T> subject, Class<T> responseType) {
    if (!subscriptionReply.hasError()) {
        establishSubscription(subject, responseType, subscriptionReply);
    } else {
        reportSubscriptionError(subject, subscriptionReply);
    }
}
 
Example #14
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void establishSubscription(
        BehaviorSubject<T> subject, Class<T> responseType, EthSubscribe subscriptionReply) {
    log.debug("Subscribed to RPC events with id {}", subscriptionReply.getSubscriptionId());
    subscriptionForId.put(
            subscriptionReply.getSubscriptionId(),
            new WebSocketSubscription<>(subject, responseType));
}
 
Example #15
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void reportSubscriptionError(
        BehaviorSubject<T> subject, BcosSubscribe subscriptionReply) {
    Response.Error error = subscriptionReply.getError();
    log.error("Subscription request returned error: {}", error.getMessage());
    subject.onError(
            new IOException(
                    String.format(
                            "Subscription request failed with error: %s", error.getMessage())));
}
 
Example #16
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> String getSubscriptionId(BehaviorSubject<T> subject) {
    return subscriptionForId.entrySet().stream()
            .filter(entry -> entry.getValue().getSubject() == subject)
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null);
}
 
Example #17
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void reportSubscriptionError(
        BehaviorSubject<T> subject, EthSubscribe subscriptionReply) {
    Response.Error error = subscriptionReply.getError();
    log.error("Subscription request returned error: {}", error.getMessage());
    subject.onError(
            new IOException(
                    String.format(
                            "Subscription request failed with error: %s", error.getMessage())));
}
 
Example #18
Source File: ObservableTest.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
@Test
void behaviorSubject_test() {
    BehaviorSubject<Object> behaviorSubject = BehaviorSubject.create();

    behaviorSubject.onNext(1L);
    behaviorSubject.onNext(2L);
    behaviorSubject.subscribe(x -> log("一郎神: " + x),
            Throwable::printStackTrace,
            () -> System.out.println("Emission completed"),
            disposable -> System.out.println("onSubscribe")
    );
    behaviorSubject.onNext(10L);
    behaviorSubject.onComplete();
}
 
Example #19
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void subscribeToEventsStream(
        Request request, BehaviorSubject<T> subject, Class<T> responseType) {

    subscriptionRequestForId.put(
            request.getId(), new WebSocketSubscription<>(subject, responseType));
    try {
        send(request, EthSubscribe.class);
    } catch (IOException e) {
        log.error("Failed to subscribe to RPC events with request id {}", request.getId());
        subject.onError(e);
    }
}
 
Example #20
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void closeSubscription(
        BehaviorSubject<T> subject, String unsubscribeMethod) {
    String subscriptionId = getSubscriptionId(subject);
    if (subscriptionId != null) {
        subscriptionForId.remove(subscriptionId);
        unsubscribeFromEventsStream(subscriptionId, unsubscribeMethod);
    } else {
        log.warn("Trying to unsubscribe from a non-existing subscription. Race condition?");
    }
}
 
Example #21
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 #22
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 #23
Source File: RecorderControllerImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private void addServiceObserverIfNeeded(
    final String sensorId,
    final List<SensorTrigger> activeTriggers,
    SensorRegistry sensorRegistry) {
  if (!latestValues.containsKey(sensorId)) {
    latestValues.put(sensorId, BehaviorSubject.<ScalarReading>create());
  }

  if (!serviceObservers.containsKey(sensorId)) {
    String serviceObserverId =
        registry.putListeners(
            sensorId,
            (timestamp, data) -> {
              if (!ScalarSensor.hasValue(data)) {
                return;
              }
              double value = ScalarSensor.getValue(data);

              // Remember latest value
              latestValues.get(sensorId).onNext(new ScalarReading(timestamp, value, sensorId));

              // Fire triggers.
              for (SensorTrigger trigger : activeTriggers) {
                if (!isRecording() && trigger.shouldTriggerOnlyWhenRecording()) {
                  continue;
                }
                if (trigger.isTriggered(value)) {
                  fireSensorTrigger(trigger, timestamp, sensorRegistry);
                }
              }
            },
            null);
    serviceObservers.put(sensorId, serviceObserverId);
  }
}
 
Example #24
Source File: RecorderControllerImpl.java    From science-journal with Apache License 2.0 5 votes vote down vote up
private MaybeSource<SensorSnapshot> makeSnapshot(String sensorId, SensorRegistry sensorRegistry)
    throws Exception {
  BehaviorSubject<ScalarReading> subject = latestValues.get(sensorId);
  if (subject == null) {
    return Maybe.empty();
  }
  final GoosciSensorSpec.SensorSpec spec = getSensorSpec(sensorId, sensorRegistry);
  return subject.firstElement().map(value -> generateSnapshot(spec, value));
}
 
Example #25
Source File: RxJavaCharacterizationTests.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Test
public void firstElementAsBehaviorSubjectChanges() {
  BehaviorSubject<String> subject = BehaviorSubject.create();
  TestObserver<String> beforeTest = subject.firstElement().test();

  subject.onNext("A");
  TestObserver<String> firstTest = subject.firstElement().test();
  firstTest.assertValue("A").assertComplete();
  beforeTest.assertValue("A").assertComplete();

  subject.onNext("B");
  TestObserver<String> secondTest = subject.firstElement().test();
  secondTest.assertValue("B").assertComplete();
}
 
Example #26
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 #27
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 #28
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 #29
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 #30
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();
}