io.reactivex.SingleSource Java Examples

The following examples show how to use io.reactivex.SingleSource. 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: SingleUnmarshaller.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Override
public SingleSource<T> apply(@NonNull Single<B> upstream) {
  Single<Buffer> unwrapped = upstream.map(unwrap::apply);
  Single<T> unmarshalled = unwrapped.flatMap(buffer -> {
    try {
      T obj;
      if (mapper != null) {
        JsonParser parser = mapper.getFactory().createParser(buffer.getBytes());
        obj = nonNull(mappedType) ? mapper.readValue(parser, mappedType) :
          mapper.readValue(parser, mappedTypeRef);
      } else {
        obj = getT(buffer, mappedType, mappedTypeRef);
      }
      return Single.just(obj);
    } catch (Exception e) {
      return Single.error(e);
    }
  });
  return unmarshalled;
}
 
Example #2
Source File: SavePasswordOperator.java    From ETHWallet with GNU General Public License v3.0 6 votes vote down vote up
@Override
    public SingleSource<Wallet> apply(Single<Wallet> upstream) {
        Wallet wallet = upstream.blockingGet();
        return Single.fromCallable(() -> wallet);
//        return passwordStore
//                .setPassword(wallet, password)
//                .onErrorResumeNext(err -> walletRepository.deleteWallet(wallet.getAddress())
//                        .lift(observer -> new DisposableCompletableObserver() {
//                            @Override
//                            public void onComplete() {
//                                observer.onError(err);
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                observer.onError(e);
//                            }
//                        }))
//                .toSingle(() -> wallet);
    }
 
Example #3
Source File: JudgeSelectionActivity.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
private void setupSearch() {
  //Add text change watcher
  compositeDisposable.add(
    RxTextView.textChangeEvents(judgeSearchBar)
      .skipInitialValue()
      .debounce(300, TimeUnit.MILLISECONDS)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(getSearchInputObserver()));

  compositeDisposable.add(publishSubject
    .debounce(300, TimeUnit.MILLISECONDS)
    .distinctUntilChanged()
    .switchMapSingle(new Function<String, SingleSource<LookupAccount>>() {
      @Override
      public SingleSource<LookupAccount> apply(String username) {
        return RetrofitServiceGenerator
          .getService()
          .getUsernames(URLS.STEEMIT_API_URL, SteemRequestBody.lookupAccounts(username))
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread());
      }
    }).subscribeWith(usernamesResponseObserver()));

  hideSearchingProgress();
}
 
Example #4
Source File: SchedulerTransformer.java    From Collection-Android with MIT License 6 votes vote down vote up
@Override
public SingleSource<T> apply(Single<T> upstream) {
    switch (mSchedulerType) {
        case _main:
            return upstream.observeOn(AndroidSchedulers.mainThread());
        case _io:
            return upstream.observeOn(RxSchedulerUtils.io(mIOExecutor));
        case _io_main:
            return upstream
                    .subscribeOn(RxSchedulerUtils.io(mIOExecutor))
                    .unsubscribeOn(RxSchedulerUtils.io(mIOExecutor))
                    .observeOn(AndroidSchedulers.mainThread());
        case _io_io:
            return upstream
                    .subscribeOn(RxSchedulerUtils.io(mIOExecutor))
                    .unsubscribeOn(RxSchedulerUtils.io(mIOExecutor))
                    .observeOn(RxSchedulerUtils.io(mIOExecutor));
        default:
            break;
    }
    return upstream;
}
 
Example #5
Source File: RxBleConnectionMock.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public Single<byte[]> readDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid,
                                         @NonNull final UUID descriptorUuid) {
    return discoverServices()
            .flatMap(new Function<RxBleDeviceServices, SingleSource<BluetoothGattDescriptor>>() {
                @Override
                public SingleSource<BluetoothGattDescriptor> apply(RxBleDeviceServices rxBleDeviceServices) {
                    return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
                }
            })
            .map(new Function<BluetoothGattDescriptor, byte[]>() {
                @Override
                public byte[] apply(BluetoothGattDescriptor bluetoothGattDescriptor) {
                    return bluetoothGattDescriptor.getValue();
                }
            });
}
 
Example #6
Source File: SavePasswordOperator.java    From trust-wallet-android-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SingleSource<Wallet> apply(Single<Wallet> upstream) {
    Wallet wallet = upstream.blockingGet();
    return passwordStore
            .setPassword(wallet, password)
            .onErrorResumeNext(err -> walletRepository.deleteWallet(wallet.address, password)
                    .lift(observer -> new DisposableCompletableObserver() {
                        @Override
                        public void onComplete() {
                            observer.onError(err);
                        }

                        @Override
                        public void onError(Throwable e) {
                            observer.onError(e);
                        }
                    }))
            .toSingle(() -> wallet);
}
 
Example #7
Source File: BuildsDetailsPresenter.java    From Varis-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Cancels build process
 */
public void cancelBuild() {
    RequestBody emptyBody = RequestBody.create(MediaType.parse("application/json"), "");
    Disposable subscription = mTravisRestClient.getApiService()
            .cancelBuild(mBuildId, emptyBody)
            .onErrorReturn(throwable -> new Object())
            .flatMap(new Function<Object, SingleSource<BuildDetails>>() {
                @Override
                public SingleSource<BuildDetails> apply(@NonNull Object o) throws Exception {
                    return mTravisRestClient.getApiService().getBuild(mRepoSlug, mBuildId);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((buildDetails, throwable) -> {
                if (throwable == null) {
                    handleBuildDetails(buildDetails);
                } else {
                    handleLoadingFailed(throwable);
                }
            });

    mSubscriptions.add(subscription);
}
 
Example #8
Source File: BuildsDetailsPresenter.java    From Varis-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Restarts build process
 */
public void restartBuild() {
    RequestBody emptyBody = RequestBody.create(MediaType.parse("application/json"), "");
    Disposable subscription = mTravisRestClient.getApiService()
            .restartBuild(mBuildId, emptyBody)
            .onErrorReturn(throwable -> new Object())
            .flatMap(new Function<Object, SingleSource<BuildDetails>>() {
                @Override
                public SingleSource<BuildDetails> apply(@NonNull Object o) throws Exception {
                    return mTravisRestClient.getApiService().getBuild(mRepoSlug, mBuildId);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((buildDetails, throwable) -> {
                if (throwable == null) {
                    handleBuildDetails(buildDetails);
                } else {
                    handleLoadingFailed(throwable);
                }
            });

    mSubscriptions.add(subscription);
}
 
Example #9
Source File: BoardTableConnection.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
public static Single<Boolean> resetStats() {
    return Single.defer((Callable<SingleSource<Boolean>>) () -> {
        BriteDatabase db = MimiApplication.getInstance().getBriteDatabase();
        BriteDatabase.Transaction transaction = db.newTransaction();

        ContentValues values = new ContentValues();

        values.put(Board.KEY_ACCESS_COUNT, 0);
        values.put(Board.KEY_LAST_ACCESSED, 0);
        values.put(Board.KEY_POST_COUNT, 0);

        int val = 0;
        try {
            val = db.update(Board.TABLE_NAME, SQLiteDatabase.CONFLICT_IGNORE, values, null, null);
            transaction.markSuccessful();
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error putting post options into the database", e);
        } finally {
            transaction.end();
        }

        return Single.just(val > 0);
    });

}
 
Example #10
Source File: RxBleConnectionMock.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public Completable writeDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid,
                                          @NonNull final UUID descriptorUuid, @NonNull final byte[] data) {
    return discoverServices()
            .flatMap(new Function<RxBleDeviceServices, SingleSource<BluetoothGattDescriptor>>() {
                @Override
                public SingleSource<BluetoothGattDescriptor> apply(RxBleDeviceServices rxBleDeviceServices) {
                    return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
                }
            })
            .doOnSuccess(new Consumer<BluetoothGattDescriptor>() {
                @Override
                public void accept(BluetoothGattDescriptor bluetoothGattDescriptor) throws Exception {
                    bluetoothGattDescriptor.setValue(data);
                }
            })
            .toCompletable();
}
 
Example #11
Source File: RxBleConnectionImpl.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public Completable writeDescriptor(
        @NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid, @NonNull final UUID descriptorUuid,
        @NonNull final byte[] data
) {
    return discoverServices()
            .flatMap(new Function<RxBleDeviceServices, SingleSource<BluetoothGattDescriptor>>() {
                @Override
                public SingleSource<BluetoothGattDescriptor> apply(RxBleDeviceServices rxBleDeviceServices) {
                    return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
                }
            })
            .flatMapCompletable(new Function<BluetoothGattDescriptor, CompletableSource>() {
                @Override
                public CompletableSource apply(BluetoothGattDescriptor bluetoothGattDescriptor) {
                    return writeDescriptor(bluetoothGattDescriptor, data);
                }
            });
}
 
Example #12
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private Single<JWT> validateSignature(SignedJWT jwt, Client client) {
    return jwkService.getKeys(client)
            .switchIfEmpty(Maybe.error(new InvalidRequestObjectException()))
            .flatMap(new Function<JWKSet, MaybeSource<JWK>>() {
                @Override
                public MaybeSource<JWK> apply(JWKSet jwkSet) throws Exception {
                    return jwkService.getKey(jwkSet, jwt.getHeader().getKeyID());
                }
            })
            .switchIfEmpty(Maybe.error(new InvalidRequestObjectException()))
            .flatMapSingle(new Function<JWK, SingleSource<JWT>>() {
                @Override
                public SingleSource<JWT> apply(JWK jwk) throws Exception {
                    // 6.3.2.  Signed Request Object
                    // To perform Signature Validation, the alg Header Parameter in the
                    // JOSE Header MUST match the value of the request_object_signing_alg
                    // set during Client Registration
                    if (jwt.getHeader().getAlgorithm().getName().equals(client.getRequestObjectSigningAlg()) &&
                            jwsService.isValidSignature(jwt, jwk)) {
                        return Single.just(jwt);
                    } else {
                        return Single.error(new InvalidRequestObjectException("Invalid signature"));
                    }
                }
            });
}
 
Example #13
Source File: RxBleConnectionImpl.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public Single<byte[]> readDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid,
                                     @NonNull final UUID descriptorUuid) {
    return discoverServices()
            .flatMap(new Function<RxBleDeviceServices, SingleSource<BluetoothGattDescriptor>>() {
                @Override
                public SingleSource<BluetoothGattDescriptor> apply(RxBleDeviceServices rxBleDeviceServices) {
                    return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid);
                }
            })
            .flatMap(new Function<BluetoothGattDescriptor, SingleSource<byte[]>>() {
                @Override
                public SingleSource<byte[]> apply(BluetoothGattDescriptor descriptor) {
                    return readDescriptor(descriptor);
                }
            });
}
 
Example #14
Source File: InTransactionSingle.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
public SingleSource<T> apply(Single<T> upstream) {
  return sqlConnection.rxSetAutoCommit(false)
    .andThen(upstream)
    .flatMap(item -> sqlConnection.rxCommit().andThen(Single.just(item)))
    .onErrorResumeNext(throwable -> {
      return sqlConnection.rxRollback().onErrorComplete()
        .andThen(sqlConnection.rxSetAutoCommit(true).onErrorComplete())
        .andThen(Single.error(throwable));
    }).flatMap(item -> sqlConnection.rxSetAutoCommit(true).andThen(Single.just(item)));
}
 
Example #15
Source File: RxBleConnectionImpl.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@Override
public Single<byte[]> writeCharacteristic(@NonNull UUID characteristicUuid, @NonNull final byte[] data) {
    return getCharacteristic(characteristicUuid)
            .flatMap(new Function<BluetoothGattCharacteristic, SingleSource<? extends byte[]>>() {
                @Override
                public SingleSource<? extends byte[]> apply(BluetoothGattCharacteristic characteristic) {
                    return writeCharacteristic(characteristic, data);
                }
            });
}
 
Example #16
Source File: RxFragment.java    From SimpleCropView with MIT License 5 votes vote down vote up
private Disposable cropImage() {
  return mCropView.crop(mSourceUri)
      .executeAsSingle()
      .flatMap(new Function<Bitmap, SingleSource<Uri>>() {
        @Override public SingleSource<Uri> apply(@io.reactivex.annotations.NonNull Bitmap bitmap)
            throws Exception {
          return mCropView.save(bitmap)
              .compressFormat(mCompressFormat)
              .executeAsSingle(createSaveUri());
        }
      })
      .doOnSubscribe(new Consumer<Disposable>() {
        @Override public void accept(@io.reactivex.annotations.NonNull Disposable disposable)
            throws Exception {
          showProgress();
        }
      })
      .doFinally(new Action() {
        @Override public void run() throws Exception {
          dismissProgress();
        }
      })
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Consumer<Uri>() {
        @Override public void accept(@io.reactivex.annotations.NonNull Uri uri) throws Exception {
          ((RxActivity) getActivity()).startResultActivity(uri);
        }
      }, new Consumer<Throwable>() {
        @Override public void accept(@io.reactivex.annotations.NonNull Throwable throwable)
            throws Exception {
        }
      });
}
 
Example #17
Source File: SingleTransformerOfGenericTypeIndicator.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
@CheckReturnValue
public SingleSource<T> apply(@NonNull Single<DataSnapshot> upstream) {
    return upstream.flatMap(new Function<DataSnapshot, SingleSource<? extends T>>() {
        @Override
        public SingleSource<? extends T> apply(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                return Single.just(dataSnapshot.getValue(typeIndicator));
            } else {
                return Single.error(new NoSuchElementException());
            }
        }
    });
}
 
Example #18
Source File: RxParser.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 拆壳
 *
 * @param <T>
 * @return
 */
public static <T> SingleTransformer<RespData<T>, T> handleSingleDataResult() {
    return new SingleTransformer<RespData<T>, T>() {
        @Override
        public SingleSource<T> apply(Single<RespData<T>> upstream) {
            return upstream
                    .map(new TransToData<T>())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

    };
}
 
Example #19
Source File: MainObserverTransformer.java    From pandroid with Apache License 2.0 5 votes vote down vote up
@Override
public SingleSource<T> apply(Single<T> upstream) {
    Single<T> tObservable = upstream
            .observeOn(AndroidSchedulers.mainThread());
    if (provider == null) {
        return tObservable;
    }
    return tObservable.compose(RxLifecycleDelegate.<T>bindLifecycle(provider));
}
 
Example #20
Source File: Snapshotter.java    From science-journal with Apache License 2.0 5 votes vote down vote up
public Single<Label> addSnapshotLabel(String experimentId, RecordingStatus status,
    List<String> ids) {
  // When experiment is loaded, add label
  return RxDataController.getExperimentById(dataController, experimentId)
      .<Label>flatMap(
          new Function<Experiment, SingleSource<? extends Label>>() {
            @Override
            public SingleSource<? extends Label> apply(Experiment e) throws Exception {
              LabelListHolder holder =
                  status.isRecording() ? e.getTrial(status.getCurrentRunId()) : e;
              return Snapshotter.this.addSnapshotLabelToHolder(e, holder, ids);
            }
          });
}
 
Example #21
Source File: RxBleConnectionMock.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@Override
public Single<BluetoothGattCharacteristic> getCharacteristic(@NonNull final UUID characteristicUuid) {
    return discoverServices()
            .flatMap(new Function<RxBleDeviceServices, SingleSource<? extends BluetoothGattCharacteristic>>() {
                @Override
                public SingleSource<? extends BluetoothGattCharacteristic> apply(RxBleDeviceServices rxBleDeviceServices)
                        throws Exception {
                    return rxBleDeviceServices.getCharacteristic(characteristicUuid);
                }
            });
}
 
Example #22
Source File: ChildHolderActivity.java    From APlayer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 根据参数(专辑id 歌手id 文件夹名 播放列表名)获得对应的歌曲信息列表
 *
 * @return 对应歌曲信息列表
 */
@WorkerThread
private List<Song> getMP3List() {
  if (mId < 0) {
    return null;
  }
  switch (mType) {
    //专辑id
    case Constants.ALBUM:
      return MediaStoreUtil.getSongsByArtistIdOrAlbumId(mId, Constants.ALBUM);
    //歌手id
    case Constants.ARTIST:
      return MediaStoreUtil.getSongsByArtistIdOrAlbumId(mId, Constants.ARTIST);
    //文件夹名
    case Constants.FOLDER:
      return MediaStoreUtil.getSongsByParentId(mId);
    //播放列表名
    case Constants.PLAYLIST:
      /* 播放列表歌曲id列表 */
      return DatabaseRepository.getInstance()
          .getPlayList(mId)
          .flatMap((Function<PlayList, SingleSource<List<Song>>>) playList ->
              DatabaseRepository.getInstance()
                  .getPlayListSongs(mContext, playList, false))
          .blockingGet();
  }
  return new ArrayList<>();
}
 
Example #23
Source File: Wrappers.java    From brave with Apache License 2.0 5 votes vote down vote up
public static <T> Single<T> wrap(
  SingleSource<T> source, CurrentTraceContext contextScoper, TraceContext assembled) {
  if (source instanceof Callable) {
    return new TraceContextCallableSingle<>(source, contextScoper, assembled);
  }
  return new TraceContextSingle<>(source, contextScoper, assembled);
}
 
Example #24
Source File: SingleTransformerOfClazz.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
@CheckReturnValue
public SingleSource<T> apply(@NonNull Single<DataSnapshot> upstream) {
    return upstream.flatMap(new Function<DataSnapshot, SingleSource<? extends T>>() {
        @Override
        public SingleSource<? extends T> apply(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                return Single.just(dataSnapshot.getValue(clazz));
            } else {
                return Single.error(new NoSuchElementException());
            }
        }
    });
}
 
Example #25
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Single<JWT> readRequestObject(String request, Client client) {
    return jweService.decrypt(request, client)
            .onErrorResumeNext(Single.error(new InvalidRequestObjectException("Malformed request object")))
            .flatMap((Function<JWT, SingleSource<JWT>>) jwt -> {
                if (jwt instanceof SignedJWT) {
                    return validateSignature((SignedJWT) jwt, client);
                } else {
                    return Single.just(jwt);
                }
            });
}
 
Example #26
Source File: RxBleConnectionImpl.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
@Override
public Single<byte[]> readCharacteristic(@NonNull UUID characteristicUuid) {
    return getCharacteristic(characteristicUuid)
            .flatMap(new Function<BluetoothGattCharacteristic, SingleSource<? extends byte[]>>() {
                @Override
                public SingleSource<? extends byte[]> apply(BluetoothGattCharacteristic characteristic) {
                    return readCharacteristic(characteristic);
                }
            });
}
 
Example #27
Source File: ServiceDiscoveryOperation.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
/**
 * Sometimes it happens that the {@link BluetoothGatt} will receive all {@link BluetoothGattService}'s,
 * {@link android.bluetooth.BluetoothGattCharacteristic}'s and {@link android.bluetooth.BluetoothGattDescriptor}
 * but it won't receive the final callback that the service discovery was completed. This is a potential workaround.
 * <p>
 * There is a change in Android 7.0.0_r1 where all data is received at once - in this situation returned services size will be always 0
 * https://android.googlesource.com/platform/frameworks/base/+/android-7.0.0_r1/core/java/android/bluetooth/BluetoothGatt.java#206
 * https://android.googlesource.com/platform/frameworks/base/+/android-6.0.1_r72/core/java/android/bluetooth/BluetoothGatt.java#205
 *
 * @param bluetoothGatt     the BluetoothGatt to use
 * @param rxBleGattCallback the RxBleGattCallback to use
 * @param timeoutScheduler  the Scheduler for timeout to use
 * @return Observable that may emit {@link RxBleDeviceServices} or {@link TimeoutException}
 */
@NonNull
@Override
protected Single<RxBleDeviceServices> timeoutFallbackProcedure(
        final BluetoothGatt bluetoothGatt,
        final RxBleGattCallback rxBleGattCallback,
        final Scheduler timeoutScheduler
) {
    return Single.defer(new Callable<SingleSource<? extends RxBleDeviceServices>>() {
        @Override
        public SingleSource<? extends RxBleDeviceServices> call() {
            final List<BluetoothGattService> services = bluetoothGatt.getServices();
            if (services.size() == 0) {
                // if after the timeout services are empty we have no other option to declare a failed discovery
                return Single.error(new BleGattCallbackTimeoutException(bluetoothGatt, BleGattOperationType.SERVICE_DISCOVERY));
            } else {
            /*
            it is observed that usually the Android OS is returning services, characteristics and descriptors in a short period of time
            if there are some services available we will wait for 5 more seconds just to be sure that
            the timeout was not triggered right in the moment of filling the services and then emit a value.
             */
                return Single
                        .timer(5, TimeUnit.SECONDS, timeoutScheduler)
                        .flatMap(new Function<Long, Single<RxBleDeviceServices>>() {
                            @Override
                            public Single<RxBleDeviceServices> apply(Long delayedSeconds) {
                                return Single.fromCallable(new Callable<RxBleDeviceServices>() {
                                    @Override
                                    public RxBleDeviceServices call() {
                                        return new RxBleDeviceServices(bluetoothGatt.getServices());
                                    }
                                });
                            }
                        });
            }
        }
    });
}
 
Example #28
Source File: LicensesFragment.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
private void loadLicenses() {
    licenseSubscription = Single.defer((Callable<SingleSource<String>>) () -> {
        InputStream rawResource = getActivity().getResources().openRawResource(rawRes);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rawResource));

        String line;
        StringBuilder sb = new StringBuilder();

        try {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            bufferedReader.close();
        } catch (IOException e) {
            // TODO You may want to include some logging here.
        }

        return Single.just(sb.toString());
    })
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(licensesBody -> {
                if (getActivity() == null || !isAdded()) return;
                if (mIndeterminateProgress != null && mWebView != null) {
                    mIndeterminateProgress.setVisibility(View.INVISIBLE);
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.loadDataWithBaseURL(null, licensesBody, "text/html", "utf-8", null);
                }
            });
}
 
Example #29
Source File: PrivacyPolicyFragment.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
private void loadLicenses() {
    // Load asynchronously in case of a very large file.
    privacyPolicyDisposable = Single.defer(new Callable<SingleSource<String>>() {
        @Override
        public SingleSource<String> call() throws Exception {
            InputStream rawResource = getActivity().getResources().openRawResource(R.raw.privacypolicy);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rawResource));

            String line;
            StringBuilder sb = new StringBuilder();

            try {
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
                bufferedReader.close();
            } catch (IOException e) {
                // TODO You may want to include some logging here.
            }

            return Single.just(sb.toString());
        }
    })
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String licensesBody) throws Exception {
                    if (getActivity() == null || !isAdded()) return;
                    mIndeterminateProgress.setVisibility(View.INVISIBLE);
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.loadDataWithBaseURL(null, licensesBody, "text/html", "utf-8", null);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.e("PrivacyPolicyFragment", "An exception occurred while displaying the privacy policy", throwable);
                }
            });
}
 
Example #30
Source File: LicensesFragment.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
private void loadLicenses() {
    licenseSubscription = Single.defer((Callable<SingleSource<String>>) () -> {
        InputStream rawResource = getActivity().getResources().openRawResource(rawRes);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rawResource));

        String line;
        StringBuilder sb = new StringBuilder();

        try {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            bufferedReader.close();
        } catch (IOException e) {
            // TODO You may want to include some logging here.
        }

        return Single.just(sb.toString());
    })
    .subscribeOn(Schedulers.computation())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(licensesBody -> {
        if (getActivity() == null || !isAdded()) return;
        if (mIndeterminateProgress != null && mWebView != null) {
            mIndeterminateProgress.setVisibility(View.INVISIBLE);
            mWebView.setVisibility(View.VISIBLE);
            mWebView.loadDataWithBaseURL(null, licensesBody, "text/html", "utf-8", null);
        }
    });
}