Set default Execution Context in ZIO

895 views Asked by At

I am trying to use a TrampolineExecutionContext in ZIO in order to test background stream subscriptions on the same thread (so I can run effect in the order I would expect).

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)
    }

In this situation, I obtain what I would expect that is:

"In Stream Element", "Inside for comprehension"

If I remove the on(trampolineExecutionContext), I would obtain "Inside for comprehension" only because I am not joining the fiber (creating a sync point).

How can I set for the entire test the default context to be trampolineExecutionContext without repeating it every time in every call or in the important calls?

1

There are 1 answers

0
Bogdan Vakulenko On BEST ANSWER

Maybe it's not exactly what you need, but you can try to override runner method of DefaultRunnableSpec and replace main context with TrampolineExecutionContext:

override def runner = {
  super.runner.withPlatform( _.withExecutor(
    Executor.fromExecutionContext(1)(
      trampolineExecutionContext
    )
  ))
}

In this case you will only need one on(trampolineExecutionContext) at the end of the test instead of two.