Java Code Examples for io.reactivex.disposables.CompositeDisposable#add()

The following examples show how to use io.reactivex.disposables.CompositeDisposable#add() . 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: CheckSourceService.java    From a with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    SharedPreferences preference = MApplication.getConfigPreferences();
    checkSourceListener = new CheckSourceListener() {
        @Override
        public void nextCheck() {
            CheckSourceService.this.nextCheck();
        }

        @Override
        public void compositeDisposableAdd(Disposable disposable) {
            compositeDisposable.add(disposable);
        }

        @Override
        public int getCheckIndex() {
            return checkIndex;
        }
    };
    threadsNum = preference.getInt(this.getString(R.string.pk_threads_num), 6);
    executorService = Executors.newFixedThreadPool(threadsNum);
    scheduler = Schedulers.from(executorService);
    compositeDisposable = new CompositeDisposable();
    updateNotification(0, "正在加载");
}
 
Example 2
Source File: ListActivity.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void wireData() {
  subscriptions = new CompositeDisposable();
  subscriptions.add(Select
      .from(ITEM)
      .where(ITEM.LIST.is(itemList))
      .orderBy(ITEM.COMPLETE.asc(), ITEM.DESCRIPTION.asc())
      .observe()
      .runQuery()
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(adapter::setData));
  subscriptions.add(Observable.combineLatest(Select
          .from(ITEM_LIST)
          .where(ITEM_LIST.ID.is(itemList.id()))
          .takeFirst()
          .observe()
          .runQuery(),
      Item.countItemsFor(itemList)
          .runQuery(),
      (itemList, count) -> String.format("%s (%s)", itemList.name(), count))
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(this::setTitle));
}
 
Example 3
Source File: BusUtil.java    From RxPay with Apache License 2.0 6 votes vote down vote up
/**
 * 保存订阅后的disposable
 * @param o
 * @param disposable
 */
public void addSubscription(Object o, Disposable disposable) {
    if (mSubscriptionMap == null) {
        mSubscriptionMap = new HashMap<>();
    }
    String key = o.getClass().getName();
    CompositeDisposable compositeDisposable = mSubscriptionMap.get(key);
    if (compositeDisposable != null) {
        compositeDisposable.add(disposable);
    } else {
        //一次性容器,可以持有多个并提供 添加和移除。
        CompositeDisposable disposables = new CompositeDisposable();
        disposables.add(disposable);
        mSubscriptionMap.put(key, disposables);
    }
}
 
Example 4
Source File: ArtistArtDownloadService.java    From Rey-MusicPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    mCompositeDisposable = new CompositeDisposable();
    mApiInterface = ApiClient.getClient().create(LastFmInterface.class);
    mApp = (Common) getApplicationContext();

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationBuilder = new Notification.Builder(this);

    mNotificationBuilder.setContentTitle(getResources().getString(R.string.downloading_artist_arts))
            .setContentText(getResources().getString(R.string.downloading_art_for))
            .setSmallIcon(R.mipmap.ic_music_file);

    startForeground(mNotificationId, mNotificationBuilder.build());

    mCompositeDisposable.add(Observable.fromCallable(() -> downloadAndUpdateArts())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(downloadAndUpdateObserver));

}
 
Example 5
Source File: AlbumsArtDownloadService.java    From Rey-MusicPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    mCompositeDisposable = new CompositeDisposable();
    mApiInterface = ApiClient.getClient().create(LastFmInterface.class);
    mApp = (Common) getApplicationContext();

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationBuilder = new Notification.Builder(this);

    mNotificationBuilder.setContentTitle(getResources().getString(R.string.downloading_album_arts))
            .setContentText(getResources().getString(R.string.downloading_art_for))
            .setSmallIcon(R.mipmap.ic_music_file);

    startForeground(mNotificationId, mNotificationBuilder.build());

    mCompositeDisposable.add(Observable.fromCallable(() -> downloadAndUpdateArts())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(downloadAndUpdateObserver));

}
 
Example 6
Source File: RxBus.java    From RxBus with Apache License 2.0 6 votes vote down vote up
public <T> void registerSubscriber(@NonNull Object observer, @NonNull CustomSubscriber<T> subscriber) {
    ObjectHelper.requireNonNull(observer, "Observer to register must not be null.");
    ObjectHelper.requireNonNull(subscriber, "Subscriber to register must not be null.");

    SUBSCRIBERS.putIfAbsent(observer.getClass(), new CopyOnWriteArraySet<CustomSubscriber<?>>());
    Set<CustomSubscriber<?>> subscribers = SUBSCRIBERS.get(observer.getClass());
    if (subscribers.contains(subscriber))
        throw new IllegalArgumentException("Subscriber has already been registered.");
    else
        subscribers.add(subscriber);

    Observable<T> observable = bus.ofType(subscriber.getEventClass())
            .observeOn(subscriber.getScheduler() == null ?
                    AndroidSchedulers.mainThread() : subscriber.getScheduler());

    Class<?> observerClass = observer.getClass();

    OBSERVERS.putIfAbsent(observerClass, new CompositeDisposable());
    CompositeDisposable composite = OBSERVERS.get(observerClass);

    composite.add(((subscriber.getFilter() == null) ? observable :
            observable.filter(subscriber.getFilter()))
            .subscribe(subscriber));
}
 
Example 7
Source File: CheckSourceService.java    From MyBookshelf with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    SharedPreferences preference = MApplication.getConfigPreferences();
    checkSourceListener = new CheckSourceListener() {
        @Override
        public void nextCheck() {
            CheckSourceService.this.nextCheck();
        }

        @Override
        public void compositeDisposableAdd(Disposable disposable) {
            compositeDisposable.add(disposable);
        }

        @Override
        public int getCheckIndex() {
            return checkIndex;
        }
    };
    threadsNum = preference.getInt(this.getString(R.string.pk_threads_num), 6);
    executorService = Executors.newFixedThreadPool(threadsNum);
    scheduler = Schedulers.from(executorService);
    compositeDisposable = new CompositeDisposable();
    updateNotification(0, "正在加载");
}
 
Example 8
Source File: RxBusDemo_Bottom2Fragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
  super.onStart();
  _disposables = new CompositeDisposable();

  Flowable<Object> tapEventEmitter = _rxBus.asFlowable().share();

  _disposables.add(
      tapEventEmitter.subscribe(
          event -> {
            if (event instanceof RxBusDemoFragment.TapEvent) {
              _showTapText();
            }
          }));

  Flowable<Object> debouncedEmitter = tapEventEmitter.debounce(1, TimeUnit.SECONDS);
  Flowable<List<Object>> debouncedBufferEmitter = tapEventEmitter.buffer(debouncedEmitter);

  _disposables.add(
      debouncedBufferEmitter
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              taps -> {
                _showTapCount(taps.size());
              }));
}
 
Example 9
Source File: UpdateBookListService.java    From a with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    SharedPreferences preference = MApplication.getConfigPreferences();
    updateBookListListener = new UpdateBookListListener() {
        @Override
        public void nextCheck() {
            UpdateBookListService.this.nextCheck();
        }

        @Override
        public void compositeDisposableAdd(Disposable disposable) {
            compositeDisposable.add(disposable);
        }

        @Override
        public int getCheckIndex() {
            return checkIndex;
        }
    };
    threadsNum = preference.getInt(this.getString(R.string.pk_threads_num), 6);
    executorService = Executors.newFixedThreadPool(threadsNum);
    scheduler = Schedulers.from(executorService);
    compositeDisposable = new CompositeDisposable();
    updateNotification(0, "正在加载");
}
 
Example 10
Source File: RxBusDemo_Bottom3Fragment.java    From RxJava-Android-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
  super.onStart();
  _disposables = new CompositeDisposable();

  ConnectableFlowable<Object> tapEventEmitter = _rxBus.asFlowable().publish();

  _disposables //
      .add(
      tapEventEmitter.subscribe(
          event -> {
            if (event instanceof RxBusDemoFragment.TapEvent) {
              _showTapText();
            }
          }));

  _disposables.add(
      tapEventEmitter
          .publish(stream -> stream.buffer(stream.debounce(1, TimeUnit.SECONDS)))
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              taps -> {
                _showTapCount(taps.size());
              }));

  _disposables.add(tapEventEmitter.connect());
}
 
Example 11
Source File: DemoCompositeDisposable.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	CompositeDisposable disposable = new CompositeDisposable();
	disposable.add(Flowable.rangeLong(10, 5).subscribe(System.out::println));
	disposable.add(Flowable.rangeLong(1, 5).subscribe(item -> System.out.println("two" + item)));

	disposable.add(Observable.create(new ObservableOnSubscribe<String>() {

		@Override
		public void subscribe(ObservableEmitter<String> emitter) throws Exception {
			// TODO Auto-generated method stub

			try {
				String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May", "Jun", "July", "Aug", "Sept", "Oct",
						"Nov", "Dec" };

				List<String> months = Arrays.asList(monthArray);

				for (String month : months) {
					emitter.onNext(month);
				}
				emitter.onComplete();
			} catch (Exception e) {
				// TODO: handle exception
				emitter.onError(e);
			}
		}
	}).subscribe(s -> System.out.println(s)));

	disposable.dispose();

	
}
 
Example 12
Source File: ScopeViewModel.java    From rxjava-RxLife with Apache License 2.0 5 votes vote down vote up
private void addDisposable(Disposable disposable) {
    CompositeDisposable disposables = mDisposables;
    if (disposables == null) {
        disposables = mDisposables = new CompositeDisposable();
    }
    disposables.add(disposable);
}
 
Example 13
Source File: ObserverUtil.java    From Learning-Resources with MIT License 5 votes vote down vote up
/**
 * @return Observer with which observable will subscribe
 */
public static <T> Observer<T> getObserver(final CompositeDisposable compositeDisposable,
                                          final WebserviceBuilder.ApiNames apiNames, final ListCallback callback) {
    return new Observer<T>() {

        @Override
        public void onSubscribe(Disposable d) {
            if (compositeDisposable != null) compositeDisposable.add(d);
        }

        @Override
        public void onNext(T value) {
            if (callback != null) callback.onListNext(value, apiNames);
        }


        @Override
        public void onError(Throwable e) {
            if (callback != null) callback.onFailure(e, apiNames);
        }

        @Override
        public void onComplete() {
            if (callback != null) callback.onListComplete(apiNames);
        }
    };
}
 
Example 14
Source File: RxBusDemo_Bottom1Fragment.java    From RxJava-Android-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
  super.onStart();
  _disposables = new CompositeDisposable();

  _disposables.add(
      _rxBus
          .asFlowable()
          .subscribe(
              event -> {
                if (event instanceof RxBusDemoFragment.TapEvent) {
                  _showTapText();
                }
              }));
}
 
Example 15
Source File: OrgUnitCascadeDialog.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    binding = DataBindingUtil.inflate(inflater, R.layout.dialog_cascade_orgunit, container, false);
    binding.title.setText(title);
    disposable = new CompositeDisposable();

    setListeners();


    disposable.add(RxTextView.textChanges(binding.orgUnitSearchEditText)
            .skipInitialValue()
            .debounce(500, TimeUnit.MILLISECONDS)
            .filter(data -> !isEmpty(data))
            .map(textTofind -> d2.organisationUnitModule().organisationUnits().byDisplayName().like("%" + textTofind.toString() + "%").blockingGet())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    this::showChips,
                    Timber::e
            ));

    disposable.add(
            Observable.fromCallable(() -> d2.organisationUnitModule().organisationUnits().blockingGet())
                    .map(ouList -> {
                        int maxLevel = -1;
                        for (OrganisationUnit ou : ouList) {
                            if (maxLevel < ou.level())
                                maxLevel = ou.level();
                        }
                        return maxLevel;
                    })
                    .map(maxLevel -> {
                        List<OrgUnitItem> orgUnitItems = new ArrayList<>();
                        for (int i = 1; i <= maxLevel; i++) {
                            OrgUnitItem orgUnitItem = new OrgUnitItem(d2.organisationUnitModule().organisationUnits(), ouSelectionType);
                            orgUnitItem.setMaxLevel(maxLevel);
                            orgUnitItem.setLevel(i);
                            orgUnitItem.setOrganisationUnitLevel(d2.organisationUnitModule().organisationUnitLevels().byLevel().eq(i).one().blockingGet());//TODO: CHECK IF OU ALREADY SELECTED
                            orgUnitItems.add(orgUnitItem);
                        }
                        return orgUnitItems;
                    })
                    .subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            this::setAdapter,
                            Timber::e
                    )
    );
    setRetainInstance(true);
    return binding.getRoot();
}
 
Example 16
Source File: OptionSetCellPopUp.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public OptionSetCellPopUp(Context context, View anchor, SpinnerViewModel model,
                      OptionSetView optionSetView) {
    super(context, anchor);
    d2 = ((App) context.getApplicationContext()).serverComponent().userManager().getD2();
    this.optionsToHide = model.getOptionsToHide();
    this.optionGroupsToHide = model.getOptionGroupsToHide();
    setOnDismissListener(menu -> dismiss());
    setOnMenuItemClickListener(item -> {
        Option selectedOption = optionsMap.get(item.getTitle().toString());
        optionSetView.onSelectOption(selectedOption);
        return false;
    });
    disposable = new CompositeDisposable();

    disposable.add(
            Single.fromCallable(() -> d2.optionModule().options()
                    .byOptionSetUid().eq(model.optionSet()))
                    .map(optionRepository -> {
                        List<String> finalOptionsToHide = new ArrayList<>();
                        if (optionsToHide!=null && !optionsToHide.isEmpty())
                            finalOptionsToHide.addAll(optionsToHide);

                        if (optionGroupsToHide!=null && !optionGroupsToHide.isEmpty()) {
                            for (String groupUid : optionGroupsToHide) {
                                finalOptionsToHide.addAll(
                                        UidsHelper.getUidsList(d2.optionModule().optionGroups().withOptions().uid(groupUid).blockingGet().options())
                                );
                            }
                        }
                        if (!finalOptionsToHide.isEmpty())
                            optionRepository = optionRepository
                                    .byUid().notIn(finalOptionsToHide);

                        return optionRepository.blockingGet();
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            this::setOptions,
                            Timber::e
                    )
    );

}
 
Example 17
Source File: TrackedRefcount.java    From akarnokd-misc with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    RxJavaAssemblyTracking.enable();
    
    System.out.println("start");

    PublishSubject<String> stringsEmitter = PublishSubject.create();

    Observable<String> combineSource = stringsEmitter
            .doOnSubscribe(d -> System.out.println("Connected!"))
            .replay(1)
            .refCount()
            .doOnSubscribe(d -> System.out.println("Subscribed!"))
            .doOnDispose(() -> System.out.println("Disposed!"));

    CompositeDisposable c = new CompositeDisposable();

    c.add(
            combineSource
                    //.subscribeOn(Schedulers.io())
                    .subscribe((string) -> System.out.println("A1:" + string))
    );
    c.add(
            combineSource
                    //.subscribeOn(Schedulers.io())
                    .subscribe((string) -> System.out.println("B1:" + string))
    );

    stringsEmitter.onNext("s1");

    Thread.sleep(100);
    c.clear();

    Thread.sleep(100);

    System.out.println("---");

    combineSource
        //.subscribeOn(Schedulers.io())
        //.subscribe((string) -> System.out.println("A2:" + string));
            .subscribe((string) -> System.out.println("A2:" + string), Throwable::printStackTrace, () -> System.out.println("Done A2"));

    combineSource
        //.subscribeOn(Schedulers.io())
            .subscribe((string) -> System.out.println("B2:" + string), Throwable::printStackTrace, () -> System.out.println("Done B2"));

    Thread.sleep(1000);

    stringsEmitter.onNext("s2");

    Thread.sleep(1000);

    stringsEmitter.onNext("s3");
    stringsEmitter.onNext("s4");
}
 
Example 18
Source File: EventInitialPresenter.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void init(EventInitialContract.View mview, String programId, String eventId, String orgInitId,
                 String programStageId) {
    this.view = mview;
    this.eventId = eventId;
    this.programId = programId;
    this.programStageId = programStageId;

    compositeDisposable = new CompositeDisposable();

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(view.getContext());

    if (eventId != null) {
        compositeDisposable
                .add(
                        Flowable
                                .zip(eventInitialRepository.event(eventId).toFlowable(BackpressureStrategy.LATEST),
                                        eventInitialRepository.getProgramWithId(programId)
                                                .toFlowable(BackpressureStrategy.LATEST),
                                        eventInitialRepository.catCombo(programId).toFlowable(BackpressureStrategy.LATEST),
                                        eventInitialRepository.programStageForEvent(eventId),
                                        eventInitialRepository.getOptionsFromCatOptionCombo(eventId),
                                        eventInitialRepository.orgUnits(programId).toFlowable(BackpressureStrategy.LATEST),
                                        Sextet::create)
                                .subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui())
                                .subscribe(sextet -> {
                                    this.program = sextet.val1();
                                    this.catCombo = sextet.val2();
                                    this.orgUnits = sextet.val5();
                                    view.setProgram(sextet.val1());
                                    view.setProgramStage(sextet.val3());
                                    view.setEvent(sextet.val0());
                                    getCatOptionCombos(catCombo, !sextet.val4().isEmpty() ? sextet.val4() : null);
                                }, Timber::d));

    } else {
        compositeDisposable
                .add(
                        Flowable
                                .zip(
                                        eventInitialRepository.getProgramWithId(programId)
                                                .toFlowable(BackpressureStrategy.LATEST),
                                        eventInitialRepository.catCombo(programId).toFlowable(BackpressureStrategy.LATEST),
                                        eventInitialRepository.orgUnits(programId).toFlowable(BackpressureStrategy.LATEST),
                                        Trio::create)
                                .subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui())
                                .subscribe(trioFlowable -> {
                                    this.program = trioFlowable.val0();
                                    this.catCombo = trioFlowable.val1();
                                    this.orgUnits = trioFlowable.val2();
                                    view.setProgram(trioFlowable.val0());
                                    getCatOptionCombos(catCombo, null);
                                }, Timber::d));
        getProgramStages(programId, programStageId);
    }

    if (eventId != null)
        getEventSections(eventId);

    if (orgInitId != null) {
        compositeDisposable.add(eventInitialRepository.getOrganisationUnit(orgInitId)
                .subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui()).subscribe(
                        organisationUnit -> view.setOrgUnit(organisationUnit.uid(), organisationUnit.displayName()),
                        Timber::d));
    }

    compositeDisposable
            .add(eventInitialRepository.accessDataWrite(programId).subscribeOn(schedulerProvider.io())
                    .observeOn(schedulerProvider.ui()).subscribe(view::setAccessDataWrite, Timber::e)

            );
}
 
Example 19
Source File: PaginationAutoFragment.java    From RxJava-Android-Samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onStart() {
  super.onStart();
  _disposables = new CompositeDisposable();

  Disposable d2 =
      _paginator
          .onBackpressureDrop()
          .doOnNext(
              i -> {
                _requestUnderWay = true;
                _progressBar.setVisibility(View.VISIBLE);
              })
          .concatMap(this::_itemsFromNetworkCall)
          .observeOn(AndroidSchedulers.mainThread())
          .map(
              items -> {
                _adapter.addItems(items);
                _adapter.notifyDataSetChanged();

                return items;
              })
          .doOnNext(
              i -> {
                _requestUnderWay = false;
                _progressBar.setVisibility(View.INVISIBLE);
              })
          .subscribe();

  // I'm using an RxBus purely to hear from a nested button click
  // we don't really need Rx for this part. it's just easy ¯\_(ツ)_/¯

  Disposable d1 =
      _bus.asFlowable()
          .filter(o -> !_requestUnderWay)
          .subscribe(
              event -> {
                if (event instanceof PaginationAutoAdapter.PageEvent) {

                  // trigger the paginator for the next event
                  int nextPage = _adapter.getItemCount();
                  _paginator.onNext(nextPage);
                }
              });

  _disposables.add(d1);
  _disposables.add(d2);

  _paginator.onNext(0);
}
 
Example 20
Source File: RxBus.java    From RxBus with Apache License 2.0 2 votes vote down vote up
public void register(@NonNull Object observer) {
    ObjectHelper.requireNonNull(observer, "Observer to register must not be null.");

    Class<?> observerClass = observer.getClass();

    if (OBSERVERS.putIfAbsent(observerClass, new CompositeDisposable()) != null)
        throw new IllegalArgumentException("Observer has already been registered.");

    CompositeDisposable composite = OBSERVERS.get(observerClass);

    Set<Class<?>> events = new HashSet<>();

    for (Method method : observerClass.getDeclaredMethods()) {

        if (method.isBridge() || method.isSynthetic())
            continue;

        if (!method.isAnnotationPresent(Subscribe.class))
            continue;

        int mod = method.getModifiers();

        if (Modifier.isStatic(mod) || !Modifier.isPublic(mod))
            throw new IllegalArgumentException("Method " + method.getName() +
                    " has @Subscribe annotation must be public, non-static");

        Class<?>[] params = method.getParameterTypes();

        if (params.length != 1)
            throw new IllegalArgumentException("Method " + method.getName() +
                    " has @Subscribe annotation must require a single argument");

        Class<?> eventClass = params[0];

        if (eventClass.isInterface())
            throw new IllegalArgumentException("Event class must be on a concrete class type.");

        if (!events.add(eventClass))
            throw new IllegalArgumentException("Subscriber for " + eventClass.getSimpleName() +
                    " has already been registered.");

        composite.add(bus.ofType(eventClass)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new AnnotatedSubscriber<>(observer, method)));
    }

}