Search code examples
scalaclientgrpcrpczio

Functionalities between calling rpc methods


Im trying to alter ZIO's example code to fit what I want, but ran into a problem. I want to implement functionalities between different rpc calls, but I can't seem to get it to work, since in below example, only the while loop, rcpMethod3() and rcpMethod4() gets executed, whereas rcpMethod1() and rcpMethod2() doesn't.

I want to execute all of the rcpMethods and the while loop.

object Client extends App {
  val clientLayer: Layer[Throwable, ClientZLayer] =
  ClientZLayer.live(
    ZManagedChannel(
      ManagedChannelBuilder.forAddress("localhost", 8980).usePlaintext()
    )
  )
  
  // rcp methods
  def rcpMethod1(): ZIO[ClientZLayer with Console, Status, Unit] = {
    for {
      response <- ClientZLayer.rcpMethod1(Greeting("Hi"))
      _ <- putStrLn(s"""Greeted: "${response.name}".""")
    } yield ()
  }
  
  // Run the code
  final def run(args: List[String]) = {
    (for {
      _ <- rcpMethod1()
      _ <- rcpMethod2()
    } yield ()).provideCustomLayer(clientLayer).exitCode

    while(condition) {
      // bla bla
    }
  
    (for {
      _ <- rcpMethod3()
      _ <- rcpMethod4()
    } yield ()).provideCustomLayer(clientLayer).exitCode
  }
}

Solution

  • The ZIO data type is a functional effect. A functional effect is a description of a workflow. This is why we have the run method at the end of the world. This run method executes the provided ZIO effect.

    All the rcpMethodN methods are ZIO effect, so they are just a description of running workflow. If you want to run these effects sequentially you should compose them using for-comprehension or flatMap like this:

    for {
      _ <- rcpMethod1()
      _ <- rcpMethod2()
      _ <- rcpMethod3()
      _ <- rcpMethod4()
    } yield ()
    
    

    The while(condition){ ... } is another mistake in your code. You should introduce these loop structs with ZIO data type. For example:

    for {
      _ <- rcpMethod1()
      _ <- rcpMethod2()
      _ <- ZIO.effect(???).repeatWhile(condition)
      _ <- rcpMethod3()
      _ <- rcpMethod4()
    } yield ()