Java Code Examples for io.reactivex.Flowable#error()

The following examples show how to use io.reactivex.Flowable#error() . 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: GeodeBackend.java    From immutables with Apache License 2.0 6 votes vote down vote up
private Publisher<?> executeInternal(Operation operation) {
  if (operation instanceof StandardOperations.Select) {
    return Flowable.fromCallable(new SyncSelect(this, (StandardOperations.Select) operation)).flatMapIterable(x -> x);
  } else if (operation instanceof StandardOperations.Update) {
    return Flowable.fromCallable(new SyncUpdate(this, (StandardOperations.Update) operation));
  } else if (operation instanceof StandardOperations.Insert) {
    return Flowable.fromCallable(new SyncInsert(this, (StandardOperations.Insert) operation));
  } else if (operation instanceof StandardOperations.Delete) {
    return Flowable.fromCallable(new SyncDelete(this, (StandardOperations.Delete) operation));
  } else if (operation instanceof StandardOperations.Watch) {
    return watch((StandardOperations.Watch) operation);
  } else if (operation instanceof StandardOperations.DeleteByKey) {
    return Flowable.fromCallable(new SyncDeleteByKey(this, (StandardOperations.DeleteByKey) operation));
  } else if (operation instanceof StandardOperations.GetByKey) {
    return Flowable.fromCallable(new SyncGetByKey(this, (StandardOperations.GetByKey) operation)).flatMapIterable(x -> x);
  }

  return Flowable.error(new UnsupportedOperationException(String.format("Operation %s not supported by %s",
          operation, GeodeBackend.class.getSimpleName())));
}
 
Example 2
Source File: OfflineAreaRepository.java    From ground-android with Apache License 2.0 6 votes vote down vote up
public Flowable<ImmutableSet<Tile>> getIntersectingDownloadedTilesOnceAndStream(
    OfflineArea offlineArea) {
  File jsonSource;

  try {
    jsonSource = fileUtil.getFileFromRawResource(R.raw.gnd_geojson, Config.GEO_JSON);
  } catch (IOException e) {
    return Flowable.error(e);
  }

  ImmutableList<Tile> tiles =
      geoJsonParser.intersectingTiles(offlineArea.getBounds(), jsonSource);

  return getDownloadedTilesOnceAndStream()
      .map(ts -> stream(tiles).filter(tiles::contains).collect(toImmutableSet()));
}
 
Example 3
Source File: NewsPreparationOperatorTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Override
public Publisher<NewsLetter> createFailedPublisher() {
    return new NewsPreparationOperator(
            Flowable.error(new RuntimeException()),
            "test"
    );
}
 
Example 4
Source File: ApiKvsProvider.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Flowable<Transaction<TransactionStateAsset>> get(String key) {
    if (!api.isAuthorized()){return Flowable.error(new Exception("Not authorized"));}
    String ownerId = api.getAccount().getAddress();

    return get(key, ownerId);
}
 
Example 5
Source File: AdamantApiWrapper.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<TransactionList> getAdamantTransactions(int type, String order) {
    if (!isAuthorized()){return Flowable.error(new NotAuthorizedException("Not authorized"));}

    return Flowable.defer(() -> api.getAdamantTransactions(account.getAddress(), type, 1, 0, order, AdamantApi.DEFAULT_TRANSACTIONS_LIMIT))
            .compose(requestControl())
            .compose(retryPolitics());
}
 
Example 6
Source File: WalletInteractor.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<CurrencyTransferEntity> getNewTransfersByCurrencyAbbr(String abbreviation) {
    try {
        SupportedWalletFacadeType supportedCurrencyType = SupportedWalletFacadeType.valueOf(abbreviation);
        if (wallets.containsKey(supportedCurrencyType)){
            WalletFacade facade = wallets.get(supportedCurrencyType);
            if (facade == null){return Flowable.error(new NullPointerException());}

            return facade.getNewTransfers();
        }
    }catch (Exception ex) {
        ex.printStackTrace();
    }

    return Flowable.error(new Exception("Not found currency facade"));
}
 
Example 7
Source File: StompClient.java    From StompProtocolAndroid with MIT License 5 votes vote down vote up
public Flowable<StompMessage> topic(@NonNull String destPath, List<StompHeader> headerList) {
    if (destPath == null)
        return Flowable.error(new IllegalArgumentException("Topic path cannot be null"));
    else if (!streamMap.containsKey(destPath))
        streamMap.put(destPath,
                Completable.defer(() -> subscribePath(destPath, headerList)).andThen(
                getMessageStream()
                        .filter(msg -> pathMatcher.matches(destPath, msg))
                        .toFlowable(BackpressureStrategy.BUFFER)
                        .doFinally(() -> unsubscribePath(destPath).subscribe())
                        .share())
        );
    return streamMap.get(destPath);
}
 
Example 8
Source File: StringsTest.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagateErrorInTheMiddleOfMultibyte() {
    Flowable<byte[]> src = Flowable.just(new byte[] { (byte) 0xc2 });
    Flowable<byte[]> err = Flowable.error(new IOException());
    CharsetDecoder charsetDecoder = Charset.forName("UTF-8").newDecoder();
    try {
        decode(Flowable.concat(src, err), charsetDecoder).toList().blockingGet();
        fail();
    } catch (RuntimeException e) {
        assertEquals(IOException.class, e.getCause().getClass());
    }
}
 
Example 9
Source File: RetryWhen.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
private static Function<ErrorAndDuration, Flowable<ErrorAndDuration>> delay(final Scheduler scheduler) {
    return new Function<ErrorAndDuration, Flowable<ErrorAndDuration>>() {
        @Override
        public Flowable<ErrorAndDuration> apply(ErrorAndDuration e) {
            if (e.durationMs() == NO_MORE_DELAYS)
                return Flowable.error(e.throwable());
            else
                return Flowable.timer(e.durationMs(), TimeUnit.MILLISECONDS, scheduler)
                        .map(com.github.davidmoten.rx2.Functions.constant(e));
        }
    };
}
 
Example 10
Source File: FlowablesTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
    just = Flowable.just(10);
    none = Flowable.error(new Exception("boo"));
    active = Flowable.fromPublisher(Future.future());
    just2 = Flowable.just(20);
}
 
Example 11
Source File: ScheduledPublisherTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Override
public Publisher<Long> createFailedPublisher() {
    return new ScheduledPublisher<>(
        () -> Flowable.error(new RuntimeException()),
        50,
        TimeUnit.MILLISECONDS,
        Executors.newSingleThreadScheduledExecutor()
    );
}
 
Example 12
Source File: TasksListEffectHandlersTest.java    From mobius-android-sample with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<Optional<Task>> getTask(@NonNull String taskId) {
  if (fail) return Flowable.error(new RuntimeException("Could not load task"));
  return Flowable.fromCallable(
      () -> {
        for (Task task : tasks) {
          if (task.id().equals(taskId)) return Optional.of(task);
        }
        return Optional.absent();
      });
}
 
Example 13
Source File: JsonRpc2_0Rx.java    From web3j with Apache License 2.0 5 votes vote down vote up
private Flowable<EthBlock> replayPastBlocksFlowableSync(
        DefaultBlockParameter startBlock,
        boolean fullTransactionObjects,
        Flowable<EthBlock> onCompleteFlowable) {

    BigInteger startBlockNumber;
    BigInteger latestBlockNumber;
    try {
        startBlockNumber = getBlockNumber(startBlock);
        latestBlockNumber = getLatestBlockNumber();
    } catch (IOException e) {
        return Flowable.error(e);
    }

    if (startBlockNumber.compareTo(latestBlockNumber) > -1) {
        return onCompleteFlowable;
    } else {
        return Flowable.concat(
                replayBlocksFlowableSync(
                        new DefaultBlockParameterNumber(startBlockNumber),
                        new DefaultBlockParameterNumber(latestBlockNumber),
                        fullTransactionObjects),
                Flowable.defer(
                        () ->
                                replayPastBlocksFlowableSync(
                                        new DefaultBlockParameterNumber(
                                                latestBlockNumber.add(BigInteger.ONE)),
                                        fullTransactionObjects,
                                        onCompleteFlowable)));
    }
}
 
Example 14
Source File: GaoxiaoUseCase.java    From CrazyDaily with Apache License 2.0 5 votes vote down vote up
private Publisher<GaoxiaoEntity.DataEntity> handleException(GaoxiaoEntity gaoxiaoEntity) {
    if (gaoxiaoEntity == null) {
        return Flowable.error(new ApiException(CodeConstant.CODE_EMPTY, "数据为空,请求个毛线!"));
    }
    List<GaoxiaoEntity.DataEntity> data = gaoxiaoEntity.getData();
    if (data == null || data.isEmpty()) {
        return Flowable.error(new ApiException(CodeConstant.CODE_EMPTY, "数据为空,请求个毛线!"));
    }
    return Flowable.fromIterable(data);
}
 
Example 15
Source File: ClientCalls.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Implements a bidirectional stream → stream call as {@link Flowable} → {@link Flowable}, where both the client
 * and the server independently stream to each other.
 */
@SuppressWarnings("unchecked")
public static <TRequest, TResponse> Flowable<TResponse> manyToMany(
        final Flowable<TRequest> flowableSource,
        final Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate,
        final CallOptions options) {

    final int prefetch = RxCallOptions.getPrefetch(options);
    final int lowTide = RxCallOptions.getLowTide(options);

    try {
        final RxSubscriberAndClientProducer<TRequest> subscriberAndGRPCProducer =
                flowableSource.subscribeWith(new RxSubscriberAndClientProducer<TRequest>());
        final RxClientStreamObserverAndPublisher<TResponse> observerAndPublisher =
            new RxClientStreamObserverAndPublisher<TResponse>(
                new com.salesforce.reactivegrpc.common.Consumer<CallStreamObserver<?>>() {
                    @Override
                    public void accept(CallStreamObserver<?> observer) {
                        subscriberAndGRPCProducer.subscribe((CallStreamObserver<TRequest>) observer);
                    }
                },
                new Runnable() {
                    @Override
                    public void run() {
                        subscriberAndGRPCProducer.cancel();
                    }
                },
                prefetch, lowTide);
        delegate.apply(observerAndPublisher);

        return Flowable.fromPublisher(observerAndPublisher);
    } catch (Throwable throwable) {
        return Flowable.error(throwable);
    }
}
 
Example 16
Source File: ReactiveRetryDummyServiceImpl.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<String> doSomethingFlowable(boolean throwException) {
    if (throwException) {
        return Flowable.error(new IllegalArgumentException("Failed"));
    }
    return Flowable.just("testMaybe");
}
 
Example 17
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends PropertySource> onPropertySourceError(Throwable throwable) {
    if (throwable instanceof ConfigurationException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example 18
Source File: ChatHistoryInteractor.java    From adamant-android with GNU General Public License v3.0 4 votes vote down vote up
@MainThread
public Flowable<List<MessageListContent>> loadMoreMessages() {
    if (chatId == null) {
        return Flowable.error(new IllegalStateException("Chat setChatId must be called"));
    }
    if (!haveMoreMessages()) {
        return Flowable.fromCallable(() -> chatsStorage.getMessagesByCompanionId(chatId));
    }
    if (loadingMessagesFlowable == null) {
        loadingMessagesFlowable = historySource.execute(chatId, getCurrentOffset(), PAGE_SIZE)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(transaction -> updateHeight(transaction.getHeight()))
                .observeOn(Schedulers.computation())
                .map(transaction -> keyStorage.combinePublicKeyWithTransaction(transaction))
                .flatMap(pair -> Flowable.just(pair)
                        .map(transaction -> (MessageListContent) messageMapper.apply(transaction))
                        .onErrorReturn(FallbackMessage::createMessageFromThrowable)
                )
                .toList()
                .toFlowable()
                .doOnNext(messages -> {
                    for (MessageListContent messageListContent : messages) {
                        chatsStorage.addMessageToChat(messageListContent);
                    }
                })
                .doOnComplete(() -> chatsStorage.updateLastMessages())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(ignored -> {
                    loadingMessagesFlowable = null;
                    currentPage++;
                })
                .observeOn(Schedulers.computation())
                .map(ignored -> chatsStorage.getMessagesByCompanionId(chatId))
                .retry(throwable -> throwable instanceof IOException)
                .doOnError(e -> {
                    loadingMessagesFlowable = null;
                    if (!(e instanceof IOException)) {
                        currentPage++;
                    }
                })
                .share();
    }
    return loadingMessagesFlowable;
}
 
Example 19
Source File: FlowableToCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
@Override
protected Flowable createInstanceFailingImmediately(RuntimeException e) {
    return Flowable.error(e);
}
 
Example 20
Source File: ZhihuNewsDetailUseCase.java    From CrazyDaily with Apache License 2.0 4 votes vote down vote up
private Publisher<ZhihuNewsDetailEntity> handleException(ZhihuNewsDetailEntity zhihuNewsDetailEntity) {
    if (zhihuNewsDetailEntity == null) {
        return Flowable.error(new ApiException(CodeConstant.CODE_EMPTY, "数据为空,请求个毛线!"));
    }
    return Flowable.just(zhihuNewsDetailEntity);
}