在ZIO中设置默认的执行上下文

问题描述

我正在尝试在ZIO中使用TrampolineExecutionContext来测试同一线程上的后台流订阅(以便可以按预期的顺序运行效果)。

testM("Using trampoline execution context") {
      (for {
        queue <- Queue.unbounded[String]
        _ <- ZStream
          .fromQueue(queue)
          .take(1)
          .foreach(el => ZIO.effect(println(s"In Stream $el")))
          .fork
        _ <- queue.offer("Element")
        _ <- ZIO.effect(println("Inside for comprehension")).on(trampolineExecutionContext)
      } yield {
        assert(1)(equalTo(1))
      }).on(trampolineExecutionContext)
    }

在这种情况下,我得到的期望是:

“在流元素中”,“对内容的理解”

如果删除on(trampolineExecutionContext),则仅由于我没有加入光纤(创建同步点)而获得“内部理解”。

如何在整个测试中将默认上下文设置为trampolineExecutionContext,而不必在每次通话或重要通话中都重复该默认上下文?

解决方法

也许这并不是您真正需要的,但是您可以尝试覆盖runner的{​​{1}}方法并将主上下文替换为DefaultRunnableSpec

TrampolineExecutionContext

在这种情况下,测试结束时您只需要一个override def runner = { super.runner.withPlatform( _.withExecutor( Executor.fromExecutionContext(1)( trampolineExecutionContext ) )) } ,而不是两个。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...