Discard all messages except the last one in a Scala actor

夙愿已清 提交于 2019-12-06 15:26:38

Meanwhile I have found a solution. You can check the mailbox size of the actor and simply skip the message if it is not 0.

val worker = new SwingWorker {
  def act() {
    while (true) {
      receive {
        case params: ExperimentParameters => {
          if( mailboxSize == 0) {
            //somehow expensive
            val result = RunExperiments.generateExperimentData(params)
            Swing.onEDT{ GuiElement.redrawWith(result) }
          }
        }
      }
    }
  }
}

Remember the last event without processing it, have a very short timeout, process the last event when you get the timeout

could look like (not tested)

while(true) {
  var lastReceived : Option[ExperimentParameters] = None
  receive {case params : ExperimentParameters => lastReceived = Some(params)}
  while (!lastReceived.isEmpty) {
    receiveWithin(0) {
      case params: ExperimentParameters => lastReceived = Some(params)
      case TIMEOUT => do your job with lastReceived.get;
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!