Developus
Developus

Reputation: 1462

Scala, ZIO - how to convert ZIO to Task and get result?

I have a method which returns some ZIO:

def method(...): ZIO[Any with clock, SomeError, Unit]

The method which calls this return Task[Unit]:

def otherMethod(..): Task[Unit] = {
   ZIO.effect(method(...))
}

The problem is when I call it with ZIO.effect I don't get result. How I should convert ZIO to Task to get result?

Upvotes: 3

Views: 2178

Answers (1)

zagyi
zagyi

Reputation: 17518

With ZIO.effect(method(...)) you get back a Task[ZIO[...]] that is rarely what you want (it's conceptually similar to a nested Future[Future[A]]).

In order to turn a ZIO[R, E, A] into a Taks[A], you have to understand that the latter is just a type alias for ZIO[Any, Throwable, A], which suggest that you have to

  • eliminate the dependency on the environment R (by providing it)
  • turn the error type E to Throwable if it's not already a sub-type of it (e.g. by .mapError)

This should work:

def otherMethod(..): Task[Unit] =
  method(...)
    .mapError(someError => new RuntimeException(s"failed with: $someError"))
    .provideLayer(Clock.live)

Upvotes: 6

Related Questions