Search code examples
scalafuturezio

How to create a small library with a "legacy" interface using ZIO (having persistent layers)


We want to create a "legacy" library with a future based interface:

trait LegacyClient {
   def aMethod(param: Param): Future[Result]
   
   def aSecondMethod(number: Int): Future[String]
}

we want to create an implementation that uses ZIO but exposes "the legacy" interface. The problem with doing

class ZIOBackedLegacyClient extends LegacyClient {
   def aMethod(param: Param): Future[Result] = runtime.unsafeRunToFuture(myImplementedZio)
   
   def aSecondMethod(number: Int): Future[String] = runtime.unsafeRunToFuture(mySecondImplementedZio)
}

The problem of that implementation is that the layers are built every time from scratch while we want the layers to be shared between the two methods and having a lifecycle of the belonging class.

Do you have any idea?

We have tried also to build a ZIO that returns the LegacyClient but with no success because the layers are not shared.

Thanks for your help!


Solution

  • You have to build a custom runtime:

    private val runtime: Runtime.Managed[ZEnv with AppEnv] = Runtime.unsafeFromLayer(finalLayer)
    

    and then using in your def methods:

    runtime.unsafeRunToFuture(MyZIOModule.zioMethod(param))