Future Behavior at IO Monad

I wrote a function that returns an IO value:

def foo(x : Int): IO[Future[Int]] = IO {
  // do some IO
  }

I am using the I / O class from Scalaz.

Then I use this expression to express it as follows:

  (for {
    _ <- foo(10)
  } yield bar()).unsafePerformIO()

Since the result of the call foois equal Future, is this Futureexecuted in a separate thread, but yieldinstantly calls bar(), or will the output wait until Futureit is completed before the call bar()?

Update:

I conducted the following experiment, and it seems that it does not give instantly:

def foo() : IO[Future[Unit]] = IO { Future.successful(bar()) }

def bar() : Unit = {
  Thread.sleep(200000);
  println("done")
}

scala> (for {
     | _ <- foo()
     | } yield "bar").unsafePerformIO()
res3: String = bar

Is there a way to handle this future asynchronously?

+4
source share
1 answer
IO { Future.successful(bar()) }

will execute bar(), wrap it Successor Failureand put the result in IO.

,

IO { Future { bar() } } // or IO { Future(bar()) }

bar() ExecutorContext.

Future(value: => T) - , , Future.successful(value: => T) .

+1

Source: https://habr.com/ru/post/1621551/


All Articles