如何在 Kotlin Arrow FX 中组合 IO 函数和其他效果

How to compose IO functions with other effects in Kotlin Arrow FX

我们经常需要在处理请求之前进行一些请求验证。使用箭头 v 0.8,典型的消息处理程序如下所示:

fun addToShoppingCart(request: AddToShoppingCartRequest): IO<Either<ShoppingCardError, ItemAddedEvent>> = fx {
    request
    .pipe (::validateShoppingCard)
    .flatMap { validatedRequest ->
        queryShoppingCart().bind().map { validatedRequest to it }         // fun queryShoppingCart(): IO<Either<DatabaseError, ShoppingCart>>
    }
    .flatMap { (validatedRequest, shoppingCart) ->
        maybeAddToShoppingCart(shoppingCart, validatedRequest)            // fun maybeAddToShoppingCart(...): Either<DomainError, ShoppingCart>
    }
    .flatMap { updatedShoppingCart ->
        storeShoppingCart(updatedShoppingCart).bind()                     // fun storeShoppingCart(ShoppingCart): IO<Either<DatabaseError, Unit>>
        .map {
            computeItemAddedEvent(updatedShoppingCart)
        }
    }
    .mapLeft(::computeShoppingCartError)
}

这似乎是一个方便且富有表现力的工作流定义。我试图在箭头 v 0.10.5 中定义类似的功能:

fun handleDownloadRequest(strUrl: String): IO<Either<BadUrl, MyObject>> = IO.fx {
    parseUrl(strUrl)                                                      // fun(String): Either<BadUrl,Url>
    .map {
        !effect{ downloadObject(it) }                                     // suspended fun downloadObject(Url): MyObject
    }
}

这会导致编译器错误 "Suspension functions can be called only within coroutine body"。原因是 EitherOptionmapflatMap 函数都不是 inline.

确实,关于 fx 的 blog post

"Soon you will find that you cannot call suspend functions inside the functions declared for Either such as the ones mentioned above, and other fan favorites like map() and handleErrorWith(). For that you need a concurrency library!"

所以问题是为什么会这样,这种组合的惯用方式是什么?

惯用的方式是

fun handleDownloadRequest(strUrl: String): IO<Either<BadUrl, MyObject>> =
    parseUrl(strUrl)
      .fold({
        IO.just(it.left())  // forward the error
      }, {
        IO { downloadObject(it) }
          .attempt() // get an Either<Throwable, MyObject>
          .map { it.mapLeft { /* Throwable to BadURL */ } } // fix the left side
      })

就我个人而言,我不会深入研究 IO,而是重写为挂起函数

suspend fun handleDownloadRequest(strUrl: String): Either<BadUrl, MyObject> =
    parseUrl(strUrl)
      .fold(::Left) { // forward the error
        Either.catch({ /* Throwable to BadURL */ }) { downloadObject(it) }
      }

发生的事情是,在 0.8.X 中,Either 的函数曾经是内联的。 意外 的副作用是您可以在任何地方调用挂起函数。虽然这很好,但它可能导致在 mapflatMap 中间抛出异常(或跳转线程或死锁),这对正确性来说很糟糕。是拐杖。

在 0.9(或者是 10?)中,我们删除了那个拐杖并在 API 中将其明确化:Either.catch。我们将 fold 保留为内联,因为它与 when 相同,因此那里没有真正的正确性权衡。

因此,建议的做法是在任何地方都使用 suspend,并且只在尝试执行线程、并行、取消、重试和调度或任何真正高级的事情时才使用 IO

对于基本用例 suspendEither.catch 就足够了。要在程序边缘调用 suspend 函数或需要桥接这些高级行为的地方,请使用 IO.

如果您想继续使用 Either,您可以定义 suspend/inline 版本的常规函数​​,风险自负;或等到 0.11 中的 IO<E, A>,您可以在其中使用 effectEither and effectMapEither.