io.vavr.control.Try.mapTry()方法的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(359)

本文整理了Java中io.vavr.control.Try.mapTry()方法的一些代码示例,展示了Try.mapTry()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Try.mapTry()方法的具体详情如下:
包路径:io.vavr.control.Try
类名称:Try
方法名:mapTry

Try.mapTry介绍

[英]Runs the given checked function if this is a Try.Success, passing the result of the current expression to it. If this expression is a Try.Failure then it'll return a new Try.Failure of type R with the original exception.

The main use case is chaining checked functions using method references:

  1. Try.of(() -> 0)
  2. .map(x -> 1 / x); // division by zero

[中]如果这是一次尝试,则运行给定的checked函数。成功,将当前表达式的结果传递给它。如果这个表达是一种尝试。如果失败,它将返回一次新的尝试。R型故障,原始异常。
主要用例是使用方法引用链接已检查的函数:

  1. Try.of(() -> 0)
  2. .map(x -> 1 / x); // division by zero

代码示例

代码示例来源:origin: vavr-io/vavr

  1. /**
  2. * Shortcut for {@code mapTry(mapper::apply)}, see {@link #mapTry(CheckedFunction1)}.
  3. *
  4. * @param <U> The new component type
  5. * @param mapper A checked function
  6. * @return a {@code Try}
  7. * @throws NullPointerException if {@code mapper} is null
  8. */
  9. @Override
  10. default <U> Try<U> map(Function<? super T, ? extends U> mapper) {
  11. Objects.requireNonNull(mapper, "mapper is null");
  12. return mapTry(mapper::apply);
  13. }

代码示例来源:origin: vavr-io/vavr

  1. default <U> Future<U> mapTry(CheckedFunction1<? super T, ? extends U> mapper) {
  2. Objects.requireNonNull(mapper, "mapper is null");
  3. return transformValue(t -> t.mapTry(mapper));
  4. }

代码示例来源:origin: vavr-io/vavr

  1. default <U> Future<U> flatMapTry(CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) {
  2. Objects.requireNonNull(mapper, "mapper is null");
  3. return run(executor(), complete ->
  4. onComplete(result -> result.mapTry(mapper)
  5. .onSuccess(future -> future.onComplete(complete::with))
  6. .onFailure(x -> complete.with(Try.failure(x)))
  7. )
  8. );
  9. }

代码示例来源:origin: resilience4j/resilience4j

  1. @Test
  2. public void decorateCheckedFunction() throws Throwable {
  3. CheckedFunction1<Integer, String> function = mock(CheckedFunction1.class);
  4. CheckedFunction1<Integer, String> decorated = RateLimiter.decorateCheckedFunction(limit, function);
  5. when(limit.getPermission(config.getTimeoutDuration()))
  6. .thenReturn(false);
  7. Try<String> decoratedFunctionResult = Try.success(1).mapTry(decorated);
  8. then(decoratedFunctionResult.isFailure()).isTrue();
  9. then(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  10. verify(function, never()).apply(any());
  11. when(limit.getPermission(config.getTimeoutDuration()))
  12. .thenReturn(true);
  13. Try secondFunctionResult = Try.success(1).mapTry(decorated);
  14. then(secondFunctionResult.isSuccess()).isTrue();
  15. verify(function, times(1)).apply(1);
  16. }

代码示例来源:origin: resilience4j/resilience4j

  1. @Test
  2. public void decorateFutureSupplier() throws Throwable {
  3. when(timeLimiter.getTimeLimiterConfig()).thenReturn(shortConfig);
  4. Future<Integer> future = EXECUTOR_SERVICE.submit(() -> {
  5. Thread.sleep(SLEEP_DURATION.toMillis());
  6. return 1;
  7. }
  8. );
  9. Supplier<Future<Integer>> supplier = () -> future;
  10. Callable<Integer> decorated = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier);
  11. Try decoratedResult = Try.success(decorated).mapTry(Callable::call);
  12. then(decoratedResult.isFailure()).isTrue();
  13. then(decoratedResult.getCause()).isInstanceOf(TimeoutException.class);
  14. then(future.isCancelled()).isTrue();
  15. when(timeLimiter.getTimeLimiterConfig())
  16. .thenReturn(longConfig);
  17. Future<Integer> secondFuture = EXECUTOR_SERVICE.submit(() -> {
  18. Thread.sleep(SLEEP_DURATION.toMillis());
  19. return 1;
  20. }
  21. );
  22. supplier = () -> secondFuture;
  23. decorated = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier);
  24. Try secondResult = Try.success(decorated).mapTry(Callable::call);
  25. then(secondResult.isSuccess()).isTrue();
  26. }

代码示例来源:origin: resilience4j/resilience4j

  1. @Test
  2. public void shouldChainDecoratedFunctions() throws ExecutionException, InterruptedException {
  3. // tag::shouldChainDecoratedFunctions[]
  4. // Given
  5. CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
  6. CircuitBreaker anotherCircuitBreaker = CircuitBreaker.ofDefaults("anotherTestName");
  7. // When I create a Supplier and a Function which are decorated by different CircuitBreakers
  8. CheckedFunction0<String> decoratedSupplier = CircuitBreaker
  9. .decorateCheckedSupplier(circuitBreaker, () -> "Hello");
  10. CheckedFunction1<String, String> decoratedFunction = CircuitBreaker
  11. .decorateCheckedFunction(anotherCircuitBreaker, (input) -> input + " world");
  12. // and I chain a function with map
  13. Try<String> result = Try.of(decoratedSupplier)
  14. .mapTry(decoratedFunction::apply);
  15. // Then
  16. assertThat(result.isSuccess()).isTrue();
  17. assertThat(result.get()).isEqualTo("Hello world");
  18. // end::shouldChainDecoratedFunctions[]
  19. CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  20. assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  21. assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
  22. metrics = anotherCircuitBreaker.getMetrics();
  23. assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  24. assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
  25. }

代码示例来源:origin: resilience4j/resilience4j

  1. @Test
  2. public void shouldChainDecoratedFunctions() throws ExecutionException, InterruptedException {
  3. // tag::shouldChainDecoratedFunctions[]
  4. // Given
  5. Bulkhead bulkhead = Bulkhead.of("test", config);
  6. Bulkhead anotherBulkhead = Bulkhead.of("testAnother", config);
  7. // When I create a Supplier and a Function which are decorated by different Bulkheads
  8. CheckedFunction0<String> decoratedSupplier
  9. = Bulkhead.decorateCheckedSupplier(bulkhead, () -> "Hello");
  10. CheckedFunction1<String, String> decoratedFunction
  11. = Bulkhead.decorateCheckedFunction(anotherBulkhead, (input) -> input + " world");
  12. // and I chain a function with map
  13. Try<String> result = Try.of(decoratedSupplier)
  14. .mapTry(decoratedFunction::apply);
  15. // Then
  16. assertThat(result.isSuccess()).isTrue();
  17. assertThat(result.get()).isEqualTo("Hello world");
  18. assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
  19. assertThat(anotherBulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
  20. // end::shouldChainDecoratedFunctions[]
  21. }

代码示例来源:origin: io.vavr/vavr

  1. /**
  2. * Shortcut for {@code mapTry(mapper::apply)}, see {@link #mapTry(CheckedFunction1)}.
  3. *
  4. * @param <U> The new component type
  5. * @param mapper A checked function
  6. * @return a {@code Try}
  7. * @throws NullPointerException if {@code mapper} is null
  8. */
  9. @Override
  10. default <U> Try<U> map(Function<? super T, ? extends U> mapper) {
  11. Objects.requireNonNull(mapper, "mapper is null");
  12. return mapTry(mapper::apply);
  13. }

代码示例来源:origin: io.vavr/vavr

  1. default <U> Future<U> mapTry(CheckedFunction1<? super T, ? extends U> mapper) {
  2. Objects.requireNonNull(mapper, "mapper is null");
  3. return transformValue(t -> t.mapTry(mapper));
  4. }

代码示例来源:origin: Tristan971/Lyrebird

  1. public <T> Try<T> doWithCurrentTwitter(final CheckedFunction1<Twitter, T> action) {
  2. return getCurrentTwitter().mapTry(action);
  3. }

代码示例来源:origin: Tristan971/Lyrebird

  1. /**
  2. * @return the updated screen name of the current user
  3. */
  4. private String getCurrentScreenName() {
  5. return sessionManager.getCurrentTwitter()
  6. .mapTry(Twitter::getScreenName)
  7. .getOrElseThrow(err -> new IllegalStateException("Current user unavailable!", err));
  8. }

代码示例来源:origin: Tristan971/Lyrebird

  1. /**
  2. * @return the Twitter {@link User} associated with this Session.
  3. */
  4. public Try<User> getTwitterUser() {
  5. final long self = accessToken.getUserId();
  6. return Try.of(twitterHandler::getTwitter).mapTry(twitter -> twitter.showUser(self));
  7. }

代码示例来源:origin: Tristan971/Lyrebird

  1. @Override
  2. public void refresh() {
  3. if (!sessionManager.isLoggedInProperty().getValue()) {
  4. LOG.debug("Logged out, not refreshing direct messages.");
  5. return;
  6. }
  7. CompletableFuture.runAsync(() -> {
  8. LOG.debug("Requesting last direct messages.");
  9. sessionManager.getCurrentTwitter()
  10. .mapTry(twitter -> twitter.getDirectMessages(20))
  11. .onSuccess(this::addDirectMessages)
  12. .onFailure(err -> LOG.error("Could not load direct messages successfully!", err));
  13. });
  14. }

代码示例来源:origin: Tristan971/Lyrebird

  1. /**
  2. * Asynchronously loads the last tweets available
  3. */
  4. public void refresh() {
  5. CompletableFuture.runAsync(() -> {
  6. if (sessionManager.getCurrentTwitter().getOrElse((Twitter) null) == null) {
  7. return;
  8. }
  9. getLocalLogger().debug("Requesting last tweets in timeline.");
  10. sessionManager.getCurrentTwitter()
  11. .mapTry(this::initialLoad)
  12. .onSuccess(this::addTweets)
  13. .onFailure(err -> getLocalLogger().error("Could not refresh!", err))
  14. .andThen(() -> isFirstCall.set(false));
  15. });
  16. }

代码示例来源:origin: Tristan971/Lyrebird

  1. /**
  2. * Asynchronously requests loading of tweets prior to the given status.
  3. *
  4. * @param loadUntilThisStatus the status whose prior tweets are requested
  5. */
  6. public void loadMoreTweets(final long loadUntilThisStatus) {
  7. CompletableFuture.runAsync(() -> {
  8. getLocalLogger().debug("Requesting more tweets.");
  9. final Paging requestPaging = new Paging();
  10. requestPaging.setMaxId(loadUntilThisStatus);
  11. sessionManager.getCurrentTwitter()
  12. .mapTry(twitter -> backfillLoad(twitter, requestPaging))
  13. .onSuccess(this::addTweets);
  14. getLocalLogger().debug("Finished loading more tweets.");
  15. });
  16. }

代码示例来源:origin: io.vavr/vavr

  1. default <U> Future<U> flatMapTry(CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) {
  2. Objects.requireNonNull(mapper, "mapper is null");
  3. return run(executor(), complete ->
  4. onComplete(result -> result.mapTry(mapper)
  5. .onSuccess(future -> future.onComplete(complete::with))
  6. .onFailure(x -> complete.with(Try.failure(x)))
  7. )
  8. );
  9. }

代码示例来源:origin: Tristan971/Lyrebird

  1. /**
  2. * @return The {@link Relationship} between the current user in the direction of the {@link #targetUserProp}.
  3. */
  4. private Relationship getRelationship() {
  5. return sessionManager.doWithCurrentTwitter(
  6. twitter -> sessionManager.currentSessionProperty()
  7. .getValue()
  8. .getTwitterUser()
  9. .mapTry(us -> twitter.showFriendship(
  10. us.getId(),
  11. targetUserProp.getValue().getId()
  12. )).get()
  13. ).getOrElseThrow((Function<? super Throwable, IllegalStateException>) IllegalStateException::new);
  14. }

相关文章