Search code examples
scalaconcurrencyfunctional-programmingfor-comprehensionzio

ZIO: How to join Fibers for Processes that run forever


I have the following ZIO program with two processes that both run forever:

    for {
      ..
      numberProvider <- numberProvider(queue).fork  // runs forever
      numberService <- numberService(queue)         // runs forever
      ..
    } yield ()

The above code works, but I was wondering if this is good practice.

There are 2 questions:

  1. Is it ok, to run the 2. process on the main program. Or should it be also a Fiber?

  2. Do I have to join the Fibers in the end, even if they run forever and therefore never reach the join?

    for {
      ..
      numberProvider <- numberProvider(queue).fork  // runs forever
      numberService <- numberService(queue)         // runs forever
      ..
      _ <- numberProvider.join // join in any case
    } yield ()
    

Solution

  • you don't have to .join fiber if they run forever.

    Note that since 1.0.0-RC17, #zio added the .daemon combinator for exactly that reason, see release note here: https://github.com/zio/zio/releases/tag/v1.0.0-RC17 and that from now on, .fork should be avoided for forever-running fibers.