ZIO: How to join Fibers for Processes that run forever
Asked Answered
G

2

6

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 ()
    
Galina answered 2/12, 2019 at 19:4 Comment(0)
F
6

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.

Fossilize answered 3/12, 2019 at 8:33 Comment(0)
G
1

From the answer of fanf42 I adjusted my code to:

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

But this did not work (changed fork to daemon). It never got to the next line.

So make sure to fork the daemon as well.

for {
      ..
      numberProvider <- numberProvider(queue).daemon.fork  // runs forever
      numberService <- numberService(queue)                // runs forever
      ..
    } yield ()
Galina answered 16/12, 2019 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.