Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ()
    
like image 587
pme Avatar asked Dec 02 '19 19:12

pme


2 Answers

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.

like image 176
fanf42 Avatar answered Sep 18 '22 01:09

fanf42


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 ()
like image 35
pme Avatar answered Sep 18 '22 01:09

pme