예제 #1
0
  private void initializeSubscriptions() {
    if (downloadsSubscription != null && !downloadsSubscription.isUnsubscribed())
      downloadsSubscription.unsubscribe();

    if (threadsNumberSubscription != null && !threadsNumberSubscription.isUnsubscribed())
      threadsNumberSubscription.unsubscribe();

    threadsNumberSubscription =
        preferences.downloadThreads().asObservable().subscribe(threadsNumber::onNext);

    downloadsSubscription =
        downloadsQueueSubject
            .lift(new DynamicConcurrentMergeOperator<>(this::downloadChapter, threadsNumber))
            .onBackpressureBuffer()
            .observeOn(AndroidSchedulers.mainThread())
            .map(download -> areAllDownloadsFinished())
            .subscribe(
                finished -> {
                  if (finished) {
                    DownloadService.stop(context);
                  }
                },
                e -> Timber.e(e.getCause(), e.getMessage()));

    if (!isRunning) {
      isRunning = true;
      runningSubject.onNext(true);
    }
  }