Java Code Examples for io.reactivex.Observable.flatMap()

The following are Jave code examples for showing how to use flatMap() of the io.reactivex.Observable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: XSnow   File: ApiRetryFunc.java   Source Code and License Vote up 6 votes
@Override
public Observable<?> apply(Observable<? extends Throwable> observable) throws Exception {
    return observable
            .flatMap(new Function<Throwable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(Throwable throwable) throws Exception {
                    if (++retryCount <= maxRetries && (throwable instanceof SocketTimeoutException
                            || throwable instanceof ConnectException)) {
                        ViseLog.d("get response data error, it will try after " + retryDelayMillis
                                + " millisecond, retry count " + retryCount);
                        return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
                    }
                    return Observable.error(ApiException.handleException(throwable));
                }
            });
}
 
Example 2
Project: XinFramework   File: RetryWithDelay.java   Source Code and License Vote up 6 votes
@Override
public ObservableSource<?> apply(@NonNull Observable<Throwable> throwableObservable) throws Exception {

    return throwableObservable
            .flatMap(new Function<Throwable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(@NonNull Throwable throwable) throws Exception {
                    if (++retryCount <= maxRetries) {
                        // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                        Log.d("get error, it will try after " + retryDelaySecond
                                + " second, retry count " + retryCount);
                        return Observable.timer(retryDelaySecond,
                                TimeUnit.SECONDS);
                    }
                    // Max retries hit. Just pass the error along.
                    return Observable.error(throwable);
                }
            });
}
 
Example 3
Project: LJFramework   File: RetryWithDelay.java   Source Code and License Vote up 6 votes
@Override
public Observable<?> apply(@NonNull Observable<? extends Throwable> attempts) throws Exception {
    return attempts.flatMap(new Function<Throwable, Observable<?>>() {
        @Override
        public Observable<?> apply(@NonNull Throwable throwable) throws Exception {
            if (++retryCount <= maxRetries) {
                // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                LogUtils.e("get error, it will try after " + retryDelayMillis +
                        " millisecond, retry count " + retryCount);
                return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
            }
            // Max retries hit. Just pass the error along.
            return Observable.error(throwable);
        }
    });
}
 
Example 4
Project: GmArchMvvm   File: RetryWithDelay.java   Source Code and License Vote up 6 votes
@Override
public ObservableSource<?> apply(@NonNull Observable<Throwable> throwableObservable) throws Exception {
    return throwableObservable
            .flatMap(new Function<Throwable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(@NonNull Throwable throwable) throws Exception {
                    if (++retryCount <= maxRetries) {
                        // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                        Log.d(TAG, "Observable get error, it will try after " + retryDelaySecond
                                + " second, retry count " + retryCount);
                        return Observable.timer(retryDelaySecond,
                                TimeUnit.SECONDS);
                    }
                    // Max retries hit. Just pass the error along.
                    return Observable.error(throwable);
                }
            });
}
 
Example 5
Project: vt-support   File: StorageImpl.java   Source Code and License Vote up 6 votes
@Override
public Observable<StorageResult> put(Observable<Entry> entries) {
  return entries.flatMap((Function<Entry, ObservableSource<StorageResult>>) entry -> {
    final String insert =
        "INSERT OR REPLACE INTO TILES(zoom_level, tile_column, tile_row, tile_data)"
            + " values (?, ?, ?, ?);";

    byte[] compressedMvt;
    try {
      compressedMvt = CompressUtil.getCompressedAsGzip(entry.getVector());
    } catch (final IOException ex) {
      throw Exceptions.propagate(ex);
    }

    Observable<Object> params = Observable.<Object>just(entry.getZoomLevel(), entry.getColumn(),
        flipY(entry.getRow(), entry.getZoomLevel()), compressedMvt);

    return dataSource.update(insert)
        .parameterStream(params.toFlowable(BackpressureStrategy.BUFFER)).counts()
        .map(integer -> new StorageResult(entry))
        .onErrorReturn(throwable -> new StorageResult(entry, new Exception(throwable)))
        .toObservable();
  });
}
 
Example 6
Project: Weather-Guru-MVP   File: ManageCityPresenter.java   Source Code and License Vote up 5 votes
@Override public void loadAutocompleteCities(Observable<String> cityQueryObservable) {
  Observable<SearchApiResponseModel> a =
      cityQueryObservable.flatMap(new Function<String, Observable<SearchApiResponseModel>>() {
        @Override public Observable<SearchApiResponseModel> apply(String s) throws Exception {
          return getDataManager().locationsApiRequest(s)
              .compose(getCompositeDisposableHelper().<SearchApiResponseModel>applySchedulers());
        }
      });

  getCompositeDisposableHelper().addDisposable(
      a.compose(getCompositeDisposableHelper().<SearchApiResponseModel>applySchedulers())
          .subscribeWith(
              new CityObserver(getMvpView(), getDataManager().getErrorHandlerHelper())));
}
 
Example 7
Project: AndroidMVPresenter   File: AbstractPresenter.java   Source Code and License Vote up 5 votes
@Override
public Observable<?> apply(Observable<? extends Throwable> observable) throws Exception {
    return observable.flatMap(new Function<Throwable, ObservableSource<?>>() {
        @Override
        public ObservableSource<?> apply(Throwable throwable) throws Exception {
            if(++retryCount <= maxRetries){
                return todoBeforeRetry.apply(throwable);
            }
            return Observable.error(throwable);
        }
    });
}
 
Example 8
Project: RxActivityResults   File: RxActivityResults.java   Source Code and License Vote up 5 votes
private Observable<ActivityResult> request(Observable<?> trigger, final Intent intent) {
    if (intent != null) {
        return trigger.flatMap(new Function<Object, Observable<ActivityResult>>() {
            @Override
            public Observable<ActivityResult> apply(@NonNull Object o) throws Exception {
                return requestImplementation(intent);
            }
        });
    } else {
        throw new IllegalArgumentException("RxActivityResults.request a non null input intent");
    }
}
 
Example 9
Project: buckaroo   File: MoreObservables.java   Source Code and License Vote up 5 votes
@Deprecated
public static <T> Observable<T> skipErrors(final Observable<Single<T>> xs) {
    Preconditions.checkNotNull(xs);
    return xs.flatMap(single -> single.map(Optional::of)
        .onErrorReturn(error -> Optional.empty())
        .flatMapObservable(optional ->
            optional.map(Observable::just).orElseGet(Observable::empty)));
}
 
Example 10
Project: android-mvvm-sample   File: MoviesRemoteRepository.java   Source Code and License Vote up 5 votes
@Override
public Observable<List<Movie>> getPopularMovies(int page) {
    Observable<DiscoverMoviesResponse> discoverMoviesResponseObservable =
            apiService.discover("popularity.desc", page, ApiUtils.getApiKey());
    return discoverMoviesResponseObservable
            .flatMap(new Function<DiscoverMoviesResponse, ObservableSource<? extends List<Movie>>>() {
                @Override
                public ObservableSource<? extends List<Movie>> apply(DiscoverMoviesResponse discoverMoviesResponse)
                        throws Exception {
                    return Observable.just(discoverMoviesResponse.getResults());
                }
            });
}
 
Example 11
Project: rxjavatraining   File: StockFinderTest.java   Source Code and License Vote up 5 votes
@Test
public void testStockPriceFinderFindTheLatestCloseBug() throws IOException {
    Observable<String> stockNames = Observable.just("M", "MSFT", "BTC", "T", "ORCL");
    Observable<String> urls = stockNames.map(s -> "https://finance.google.com/finance/historical?output=csv&q=" + s);
    Observable<String> contentObservable = urls.flatMap(u -> Observable.fromFuture(createFuture(u)).onErrorResumeNext((Throwable e) -> Observable.empty()));
    Observable<String> lineObservable = contentObservable.doOnNext(s -> System.out.println(">>>>" + s)).flatMap(doc ->
            Observable.fromArray(doc.split("\n")).skip(1).take(1));
    Observable<Tuple2<String, Double>> tupleObservable = stockNames.zipWith(lineObservable.map(s -> s.split(",")[4]).map(Double::parseDouble), Tuple2::new);
    tupleObservable.subscribe(System.out::println);
}
 
Example 12
Project: simple-runtime-permission   File: RxSimpleRuntimePermissionTransform.java   Source Code and License Vote up 5 votes
@Override
public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
    return upstream.flatMap(new Function<T, ObservableSource<T>>() {
        @Override
        public ObservableSource<T> apply(@NonNull final T t) throws Exception {
            return Observable.create(new ObservableOnSubscribe<T>() {
                @Override
                public void subscribe(@NonNull final ObservableEmitter<T> e) throws Exception {
                    SimpleRuntimePermissionHelper.with(mActivity)
                            .permission(permissions)
                            .showPermissionRationaleListener(showRequestPermissionRationaleListener)
                            .execute(new PermissionListener() {
                                @Override
                                public void onAllPermissionGranted() {
                                    e.onNext(t);
                                    e.onComplete();
                                }

                                @Override
                                public void onPermissionRefuse(PermissionRefuseResultHelper resultHelper) {
                                    e.onError(
                                            new PermissionException(resultHelper)
                                    );
                                }
                            });
                }
            });
        }
    });
}
 
Example 13
Project: gigreminder   File: EditArtistPresenter.java   Source Code and License Vote up 5 votes
private Observable<Result> loadArtist(Observable<LoadArtistEvent> events) {
    return events.flatMap(event -> {
        if (!artistId.isPresent()) {
            throw new RuntimeException("An artist id shouldn't be empty");
        }

        return getRepository().getArtist(artistId.getValue())
                .map(LoadArtistResult::success)
                .onErrorReturn(LoadArtistResult::error)
                .toObservable()
                .startWith(LoadArtistResult.IN_PROGRESS);
    });
}
 
Example 14
Project: gigreminder   File: EditArtistPresenter.java   Source Code and License Vote up 5 votes
private Observable<Result> saveArtist(Observable<SaveArtistEvent> events) {
    return events.flatMap(event -> {
        String newName = event.getName();

        if (newName.isEmpty()) {
            SaveArtistResult result = SaveArtistResult.Builder.createFillError()
                    .nameIsEmpty(true)
                    .build();

            return Observable.just(result);
        }

        EditArtistUiModel uiModel = event.getUiModel();
        Completable completable;

        if (uiModel.isArtistNew()) {
            Artist newArtist = new Artist(newName);
            completable = getRepository().saveArtist(newArtist);
        } else {
            Artist initialArtist = uiModel.getInitialArtist().getValue();
            Artist updatedArtist = new Artist(initialArtist.getId(), newName);
            completable = getRepository().updateArtist(updatedArtist);
        }

        return completable
                .toSingleDefault(SaveArtistResult.SUCCESS)
                .onErrorReturn(t -> {
                    if (t instanceof NotUniqueArtistException) {
                        return SaveArtistResult.Builder.createFillError()
                                .nameIsNotUnique(true)
                                .build();
                    }

                    return SaveArtistResult.SAVING_ERROR;
                })
                .toObservable()
                .startWith(SaveArtistResult.IN_PROGRESS);
    });
}
 
Example 15
Project: SuperHttp   File: ApiRetryFunc.java   Source Code and License Vote up 5 votes
@Override
public Observable<?> apply(Observable<? extends Throwable> observable) throws Exception {
    return observable
            .flatMap(new Function<Throwable, ObservableSource<?>>() {
                @Override
                public ObservableSource<?> apply(Throwable throwable) throws Exception {
                    if (++retryCount <= maxRetries && (throwable instanceof SocketTimeoutException
                            || throwable instanceof ConnectException)) {
                        return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
                    }
                    return Observable.error(ApiException.handleException(throwable));
                }
            });
}