在 运行 个未来之后返回 IO fiber/thread

Get back to IO fiber/thread after running a future

我有一些 cat IO 操作,然后是 Future。简体:

IO(getValue())
  .flatMap(v => IO.fromFuture(IO(blockingProcessValue(v)))(myBlockingPoolContextShift))
  .map(moreProcessing)

所以我在 IO 中有一些值,然后我需要使用 returns Future 的库做一些阻塞操作,然后我需要对返回的值做一些更多的处理Future

Future 在专用线程池上运行 - 到目前为止一切顺利。问题是在 Future 完成之后。 moreProcessingFuture 与 运行 相同的线程上运行。

有没有办法回到线程 getValue() 是 运行?

在聊天中讨论后,结论是 OP 唯一需要做的就是使用适当的 (compute)[=23= 在应用程序入口点创建一个 ContextShift ] EC然后传给包含这个方法的class

// Entry point

val computeEC = ???
val cs = IO.contextShift(computeEC)
val myClass = new MyClass(cs, ...)

// Inside the method on MyClass
IO(getValue())
  .flatMap(v => IO.fromFuture(IO(blockingProcessValue(v)))(myBlockingPoolContextShift))
  .flatTap(_ => cs.shift)
  .map(moreProcessing)

Scastie 展示了一种使用 BlockerTypelevel 生态系统中常见但并不真正适合 OP 的其他技术的方法用例;无论如何,我发现它对未来可能遇到类似问题的读者很有用