从 Future 顺序执行 IO
Sequential execution of IO from Future
我有两个 IO 的简单组合,可以向 Telegram 机器人发送消息
def send:Future[Message] = request(SendMessage(chatID, msg))
如何在greeting
中组合IO每次在"first"之后得到输出"second"。
我尝试使用 *>, flatMap, IO.fromFuture 但结果不同。
first
second
second
first
def greeting(chatId: Long): IO[Unit] =
IO(request(SendMessage(chatId, "first"))) *>
IO(request(SendMessage(chatId, "second")))
override def onMessage(message: Message) = message.text match {
case Some(_) => greeting(message.chat.id)
.unsafeRunAsyncAndForget()
}
以下代码片段有效,它不会开始第二个 IO / Future
直到第一个完成。
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.effect.IO
def send(message: => String): Future[Unit] =
Future {
Thread.sleep(2000);
println(message)
}
def greeting: IO[Unit] =
for {
_ <- IO.fromFuture(IO(send("First")))
_ <- IO.fromFuture(IO(send("Second")))
} yield ()
greeting.unsafeRunAsyncAndForget()
我有两个 IO 的简单组合,可以向 Telegram 机器人发送消息
def send:Future[Message] = request(SendMessage(chatID, msg))
如何在greeting
中组合IO每次在"first"之后得到输出"second"。
我尝试使用 *>, flatMap, IO.fromFuture 但结果不同。
first
second
second
first
def greeting(chatId: Long): IO[Unit] =
IO(request(SendMessage(chatId, "first"))) *>
IO(request(SendMessage(chatId, "second")))
override def onMessage(message: Message) = message.text match {
case Some(_) => greeting(message.chat.id)
.unsafeRunAsyncAndForget()
}
以下代码片段有效,它不会开始第二个 IO / Future
直到第一个完成。
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.effect.IO
def send(message: => String): Future[Unit] =
Future {
Thread.sleep(2000);
println(message)
}
def greeting: IO[Unit] =
for {
_ <- IO.fromFuture(IO(send("First")))
_ <- IO.fromFuture(IO(send("Second")))
} yield ()
greeting.unsafeRunAsyncAndForget()