3

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?

Developus
  • 1,400
  • 2
  • 14
  • 50

1 Answers1

6

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)
zagyi
  • 17,223
  • 4
  • 51
  • 48
  • 3
    Small point but conceptually it is more similar to a `Future[() => Future[A]]` since a `Future[Future[A]]` is already processing even if not flattened, whereas `Task[Task[A]]` will do no meaningful work unless it gets flattened – paulpdaniels May 19 '21 at 03:37