简体   繁体   English

如何实现Future [Either [L,R]]的flatMap方法

[英]How to implement flatMap method of Future[Either[L, R]]

Our app uses a lot of Future[Either[Error, R]] to return either a result or an error object. 我们的应用程序使用了很多Future[Either[Error, R]]返回结果或错误对象。 I would like to create a new class that merges the two so it can be use in for-comprehensions, ie if a function is successful (returns a Right), the next function is called, else return Error. 我想创建一个将两者合并的新类,以便可以用于理解,即,如果一个函数成功(返回一个Right),则调用下一个函数,否则返回Error。

I've done the map method, but has trouble with flatMap . 我已经完成了map方法,但是在flatMap上遇到了麻烦。

class FutureEither[L, R](val future: Future[Either[L, R]]) {
  def map[S](f: R => S)(implicit executor: ExecutionContext): FutureEither[L, S] = {
    val result = future.map {
      case Right(r)    => Right(f(r))
      case Left(error) => Left(error)
    }
    new FutureEither(result)
  }

  def flatMap[S](f: R => FutureEither[L, S])(implicit executor: ExecutionContext): FutureEither[L, S] = ???
}

Would be great if someone can help me implement it, or general improvement suggestions thanks. 如果有人可以帮助我实施它,或者对总体改进的建议表示感谢,那就太好了。

Pretty much the same, just do future.flatMap instead of future.map . 几乎相同,只是执行future.flatMap而不是future.map And wrap the left case in a future: 并在将来包装左箱:

def flatMap[S](f: R => FutureEither[L, S])(implicit executor: ExecutionContext): FutureEither[L, S] = {
  new FutureEither(future.flatMap{
    case Right(r) => f(r).future
    case Left(error) => Future(Left(error))
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM