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

The following examples show how to use io.reactivex.subjects.BehaviorSubject#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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 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: RxFeaturesAdapter.java    From FeatureAdapter with Apache License 2.0 4 votes vote down vote up
/**
 * Calculates each feature's new items and diff in parallel in the computation scheduler pool,
 * then dispatches feature updates to adapter in feature order.
 *
 * @param modelObservable the stream of models
 * @return an observable of {@link FeatureUpdate} for tracking the adapter changes.
 */
public Flowable<List<FeatureUpdate>> updateFeatureItems(Observable<MODEL> modelObservable) {
  // the ticker observable is gonna emit an item every time all the
  // list of items from all the feature controllers have been computed
  // so we just process the model instances one at a time
  // this is meant to be a very fine grained back pressure mechanism.
  final Object tick = new Object();
  final BehaviorSubject<Object> tickObservable = BehaviorSubject.create();
  tickObservable.onNext(tick);
  return modelObservable
      .observeOn(mainThread())
      .zipWith(tickObservable, (model, t) -> model)
      .toFlowable(BackpressureStrategy.LATEST)
      .flatMap(
          model ->
              fromIterable(getFeatureControllers())
                  .flatMap(
                      // each feature controller receives a fork of the model observable
                      // and compute its items in parallel, and then updates the UI ASAP
                      // but we still aggregate all the list to be sure to pace the model
                      // observable
                      // correctly using the tick observable
                      feature ->
                          just(feature)
                              .observeOn(computation())
                              .map(featureController -> toFeatureUpdate(featureController, model))
                              .filter(featureUpdate -> featureUpdate.newItems != null && featureUpdate.diffResult != null)
                  )
                  // collect all observable of feature updates in a list in feature order
                  .toSortedList(featureUpdateComparator::compare)
                  .observeOn(mainThread())
                  // dispatch each feature update in order to the adapter
                  // (this also updates the internal adapter state)
                  .map(this::dispatchFeatureUpdates)
                  .map(
                      list -> {
                        tickObservable.onNext(tick);
                        if (recyclerView != null) {
                          recyclerView.setItemViewCacheSize(getItemCount());
                        }
                        return list;
                      }).toFlowable());
}
 
Example 11
Source File: ThreadDump.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<List<ThreadInfo>> createSubject() {
    return BehaviorSubject.create();
}
 
Example 12
Source File: Battery.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<BatteryInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 13
Source File: BehaviorSubjectExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 4 votes vote down vote up
private void doSomeWork() {

        BehaviorSubject<Integer> source = BehaviorSubject.create();

        source.subscribe(getFirstObserver()); // it will get 1, 2, 3, 4 and onComplete

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

        /*
         * it will emit 3(last emitted), 4 and onComplete for second observer also.
         */
        source.subscribe(getSecondObserver());

        source.onNext(4);
        source.onComplete();

    }
 
Example 14
Source File: MethodCanary.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<MethodsRecordInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 15
Source File: Heap.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<HeapInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 16
Source File: Pss.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<PssInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 17
Source File: RxJava2Proxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static RxJava2SubjProxy behaviorSubjectProxy() {
    return new RxJava2SubjProxy(BehaviorSubject.create(), Roxy.TePolicy.PASS);
}
 
Example 18
Source File: Cpu.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<CpuInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 19
Source File: Startup.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<StartupInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example 20
Source File: Sandbox.java    From Reactive-Android-Programming with MIT License 3 votes vote down vote up
private static void demo3() {
    Subject<String> subject = BehaviorSubject.create();

    Observable.interval(0, 2, TimeUnit.SECONDS)
            .map(v -> "A" + v)
            .subscribe(subject);

    subject.subscribe(v -> log(v));

    Observable.interval(1, 1, TimeUnit.SECONDS)
            .map(v -> "B" + v)
            .subscribe(subject);


}