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

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

本文整理了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:

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

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

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

代码示例

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

/**
 * Shortcut for {@code mapTry(mapper::apply)}, see {@link #mapTry(CheckedFunction1)}.
 *
 * @param <U>    The new component type
 * @param mapper A checked function
 * @return a {@code Try}
 * @throws NullPointerException if {@code mapper} is null
 */
@Override
default <U> Try<U> map(Function<? super T, ? extends U> mapper) {
  Objects.requireNonNull(mapper, "mapper is null");
  return mapTry(mapper::apply);
}

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

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

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

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

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

@Test
public void decorateCheckedFunction() throws Throwable {
  CheckedFunction1<Integer, String> function = mock(CheckedFunction1.class);
  CheckedFunction1<Integer, String> decorated = RateLimiter.decorateCheckedFunction(limit, function);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try<String> decoratedFunctionResult = Try.success(1).mapTry(decorated);
  then(decoratedFunctionResult.isFailure()).isTrue();
  then(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(function, never()).apply(any());
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondFunctionResult = Try.success(1).mapTry(decorated);
  then(secondFunctionResult.isSuccess()).isTrue();
  verify(function, times(1)).apply(1);
}

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

@Test
public void decorateFutureSupplier() throws Throwable {
  when(timeLimiter.getTimeLimiterConfig()).thenReturn(shortConfig);
  Future<Integer> future = EXECUTOR_SERVICE.submit(() -> {
        Thread.sleep(SLEEP_DURATION.toMillis());
        return 1;
      }
  );
  Supplier<Future<Integer>> supplier = () -> future;
  Callable<Integer> decorated = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier);
  Try decoratedResult = Try.success(decorated).mapTry(Callable::call);
  then(decoratedResult.isFailure()).isTrue();
  then(decoratedResult.getCause()).isInstanceOf(TimeoutException.class);
  then(future.isCancelled()).isTrue();
  when(timeLimiter.getTimeLimiterConfig())
      .thenReturn(longConfig);
  Future<Integer> secondFuture = EXECUTOR_SERVICE.submit(() -> {
        Thread.sleep(SLEEP_DURATION.toMillis());
        return 1;
      }
  );
  supplier = () -> secondFuture;
  decorated = TimeLimiter.decorateFutureSupplier(timeLimiter, supplier);
  Try secondResult = Try.success(decorated).mapTry(Callable::call);
  then(secondResult.isSuccess()).isTrue();
}

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

@Test
public void shouldChainDecoratedFunctions() throws ExecutionException, InterruptedException {
  // tag::shouldChainDecoratedFunctions[]
  // Given
  CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
  CircuitBreaker anotherCircuitBreaker = CircuitBreaker.ofDefaults("anotherTestName");
  // When I create a Supplier and a Function which are decorated by different CircuitBreakers
  CheckedFunction0<String> decoratedSupplier = CircuitBreaker
      .decorateCheckedSupplier(circuitBreaker, () -> "Hello");
  CheckedFunction1<String, String> decoratedFunction = CircuitBreaker
      .decorateCheckedFunction(anotherCircuitBreaker, (input) -> input + " world");
  // and I chain a function with map
  Try<String> result = Try.of(decoratedSupplier)
      .mapTry(decoratedFunction::apply);
  // Then
  assertThat(result.isSuccess()).isTrue();
  assertThat(result.get()).isEqualTo("Hello world");
  // end::shouldChainDecoratedFunctions[]
  CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
  metrics = anotherCircuitBreaker.getMetrics();
  assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
  assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
}

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

@Test
public void shouldChainDecoratedFunctions() throws ExecutionException, InterruptedException {
  // tag::shouldChainDecoratedFunctions[]
  // Given
  Bulkhead bulkhead = Bulkhead.of("test", config);
  Bulkhead anotherBulkhead = Bulkhead.of("testAnother", config);
  // When I create a Supplier and a Function which are decorated by different Bulkheads
  CheckedFunction0<String> decoratedSupplier
    = Bulkhead.decorateCheckedSupplier(bulkhead, () -> "Hello");
  CheckedFunction1<String, String> decoratedFunction
    = Bulkhead.decorateCheckedFunction(anotherBulkhead, (input) -> input + " world");
  // and I chain a function with map
  Try<String> result = Try.of(decoratedSupplier)
              .mapTry(decoratedFunction::apply);
  // Then
  assertThat(result.isSuccess()).isTrue();
  assertThat(result.get()).isEqualTo("Hello world");
  assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
  assertThat(anotherBulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
  // end::shouldChainDecoratedFunctions[]
}

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

/**
 * Shortcut for {@code mapTry(mapper::apply)}, see {@link #mapTry(CheckedFunction1)}.
 *
 * @param <U>    The new component type
 * @param mapper A checked function
 * @return a {@code Try}
 * @throws NullPointerException if {@code mapper} is null
 */
@Override
default <U> Try<U> map(Function<? super T, ? extends U> mapper) {
  Objects.requireNonNull(mapper, "mapper is null");
  return mapTry(mapper::apply);
}

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

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

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

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

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

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

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

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

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

@Override
public void refresh() {
  if (!sessionManager.isLoggedInProperty().getValue()) {
    LOG.debug("Logged out, not refreshing direct messages.");
    return;
  }
  CompletableFuture.runAsync(() -> {
    LOG.debug("Requesting last direct messages.");
    sessionManager.getCurrentTwitter()
           .mapTry(twitter -> twitter.getDirectMessages(20))
           .onSuccess(this::addDirectMessages)
           .onFailure(err -> LOG.error("Could not load direct messages successfully!", err));
  });
}

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

/**
 * Asynchronously loads the last tweets available
 */
public void refresh() {
  CompletableFuture.runAsync(() -> {
    if (sessionManager.getCurrentTwitter().getOrElse((Twitter) null) == null) {
      return;
    }
    getLocalLogger().debug("Requesting last tweets in timeline.");
    sessionManager.getCurrentTwitter()
           .mapTry(this::initialLoad)
           .onSuccess(this::addTweets)
           .onFailure(err -> getLocalLogger().error("Could not refresh!", err))
           .andThen(() -> isFirstCall.set(false));
  });
}

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

/**
 * Asynchronously requests loading of tweets prior to the given status.
 *
 * @param loadUntilThisStatus the status whose prior tweets are requested
 */
public void loadMoreTweets(final long loadUntilThisStatus) {
  CompletableFuture.runAsync(() -> {
    getLocalLogger().debug("Requesting more tweets.");
    final Paging requestPaging = new Paging();
    requestPaging.setMaxId(loadUntilThisStatus);
    sessionManager.getCurrentTwitter()
           .mapTry(twitter -> backfillLoad(twitter, requestPaging))
           .onSuccess(this::addTweets);
    getLocalLogger().debug("Finished loading more tweets.");
  });
}

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

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

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

/**
 * @return The {@link Relationship} between the current user in the direction of the {@link #targetUserProp}.
 */
private Relationship getRelationship() {
  return sessionManager.doWithCurrentTwitter(
      twitter -> sessionManager.currentSessionProperty()
                   .getValue()
                   .getTwitterUser()
                   .mapTry(us -> twitter.showFriendship(
                       us.getId(),
                       targetUserProp.getValue().getId()
                   )).get()
  ).getOrElseThrow((Function<? super Throwable, IllegalStateException>) IllegalStateException::new);
}

相关文章