2

I am trying to collect health information for my application as

class HealthMonitor extends Actor with ActorLogging {
  val statusReporter = new StatusReporter
  val versionInfo = context.actorOf(Props[VersionInfo], "versionInfo")
  val memoryInfo = context.actorOf(Props[MemoryInfo], "memoryInfo")

  def receive = LoggingReceive {
    case HealthReportRequest => log.debug("Generating Health Report")
      println("Generating Health Report")
      // todo (harit): should be concurrent calls and collect results
      versionInfo ! VersionInfoRequest
      memoryInfo ! MemoryInfoRequest
  }
}

What I need
I need a way wherein I can collect responses from versionInfo, memoryInfo, and some other info later into 1 response and send it somewhere

and I do not want a sequential or want to block the calls, what is the best way?

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • Do an ask (?) instead of a tell (!) and each message will be sent without blocking and the responses will be in two futures. Then you can combine those two futures into one response with a for comprehension. – Gangstead Aug 18 '15 at 20:07

1 Answers1

2

I'll make a guess you meant an ask instead of a tell because you're talking about responses, so the code should be

def receive = LoggingReceive {
  case HealthReportRequest => log.debug("Generating Health Report")
    println("Generating Health Report")
    versionInfo ? VersionInfoRequest
    memoryInfo ? MemoryInfoRequest
}

Then you can type the futures.

def receive = LoggingReceive {
  case HealthReportRequest =>
    versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    memoryInfo ? MemoryInfoRequest mapTo[VersionInfo]
}

And then combine

def receive = LoggingReceive {
  case HealthReportRequest =>
    val version = versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    val memory = (memoryInfo ? MemoryInfoRequest mapTo[VersionInfo])
    version.flatMap(v =>
      memory.map(m =>
        fun(v, m)
    ))
}

or via for (not sure on the syntax)

def receive = LoggingReceive {
  case HealthReportRequest =>
    val version = versionInfo ? VersionInfoRequest mapTo[VersionInfo]
    val memory = (memoryInfo ? MemoryInfoRequest mapTo[VersionInfo])
    for {
      v <- version
      m <- memory
    } yield fun(v, m)
}
Reactormonk
  • 21,472
  • 14
  • 74
  • 123
  • I think you would also want your version and memory requests to be parallel in this case. – Tyth Aug 19 '15 at 12:19
  • I mean you last code blocks: one with flatMap and Map and one with for comprehension. There you make two sequential requests. The seconds one waits when first is finished. – Tyth Aug 19 '15 at 12:28
  • You're right on that, got a suggestion how to improve that? `Future.sequence` doesn't apply here. – Reactormonk Aug 19 '15 at 12:31
  • I don't know any other way other than initializing you requests first, assigning returning futures to some variables, and then waiting for them in "for {}" block or via map/flatMap. – Tyth Aug 19 '15 at 12:36