从Future顺序执行IO

时间:2019-04-27 12:51:19

标签: scala cats-effect

我将两个IO的简单组合与向Telegram bot发送消息

def send:Future[Message] = request(SendMessage(chatID, msg))

如何每次都将greeting中的IO组合到输出“第二”之后的“第二”。 我尝试使用*>,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()
  }

1 个答案:

答案 0 :(得分:1)

以下代码段有效,直到第一个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()