PersistentActor无法在Future onComplete中调用持久化处理程序

时间:2015-07-06 05:54:40

标签: scala akka akka-persistence

我使用PersistentActor很新, 当我尝试从未来的onComplete调用updateState时,失败,没有什么是愉快的,尝试调试它,我确实得到了持久调用但没有进入updateState

trait Event
case class Cmd(data: String)
case class Evt(data: String) extends Event

class BarActor extends PersistentActor{
  implicit val system = context.system
  implicit val executionContext = system.dispatcher
  def updateState(event: Evt): Unit ={
    println("Updating state")
    state = state.updated(event)  
    sender() ! state

  }
  def timeout(implicit ec: ExecutionContext) =
    akka.pattern.after(duration = 2 seconds, using = system.scheduler)(Future.failed(new TimeoutException("Got timed out!")))

  val receiveCommand: Receive = {
    case Cmd(data) =>

      def anotherFuture(i: Int)(implicit system: ActorSystem) = {
        val realF = Future {
          i % 2 match {
            case 0 =>
              Thread.sleep(100)
            case _ =>
              Thread.sleep(500)
          }
          i
        }
        Future.firstCompletedOf(Seq(realF, timeout))
          .recover {
          case _ => -1
        }
      }
      val res = (1 to 10).map(anotherFuture(_))
      val list = Future.sequence(res)
      list.onComplete{
        case _ =>
          persist(Evt("testing"))(updateState)
      }
  }
}

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

  list.onComplete {
    case _ => self ! Evt("testing")
  }

并将其添加到receiveCommand

case evt: Evt =>
  persist(Evt("testing"))(updateStates)