2

In my existing Scala code I replaced Thread.sleep(10000) with ZIO.sleep(Duration.fromScala(10.seconds)) with the understanding that it won't block thread from the thread pool (performance issue). When program runs it does not wait at this line (whereas of course in first case it does). Do I need to add any extra code for ZIO method to work ?

Adding code section from Play+Scala code:

    def sendMultipartEmail = Action.async(parse.multipartFormData) { request =>
    .....
    //inside this controller below method is called
         def retryEmailOnFail(pList: ListBuffer[JsObject], content: String) = {
               if (!sendAndGetStatus(pList, content)) {
                  println("<--- email sending failed - retry once after a delay")
                  ZIO.sleep(Duration.fromScala(10.seconds))
                  println("<--- retrying email sending after a delay")
                  finalStatus = finalStatus && sendAndGetStatus(pList, content)
               } else {
                  finalStatus = finalStatus && true
               }
            }
   .....
    }
NKM
  • 602
  • 1
  • 6
  • 18
  • 1
    Can you share the whole code? – Gaël J Jul 07 '21 at 17:44
  • You haven't understood that **ZIO** isn't doing anything, it is just a description of a program; it isn't run. And if you run it there, it will block the thread. You simply can't just drop **ZIO** _(or any other `IO` monad)_ into a codebase that wasn't designed to be used with them and get its benefits out of the box. – Luis Miguel Mejía Suárez Jul 14 '21 at 14:26

1 Answers1

1

As you said, ZIO.sleep will only suspend the fiber that is running, not the operating system thread.

If you want to start something after sleeping, you should just chain it after the sleep:

// value 42 will only be computed after waiting for 10s
val io = ZIO.sleep(Duration.fromScala(10.seconds)).map(_ => 42) 
francoisr
  • 4,407
  • 1
  • 28
  • 48
  • I tried adding the ```map``` but probbaly I am not doing it right. Your suggestion is welcome. I added the code section above. – NKM Jul 14 '21 at 09:45