sender inside a future

前端 未结 3 791
感情败类
感情败类 2020-11-27 20:07

I have an actor which on receiving a message, searches the filesystem for a file and returns the full path of the File.

To keep it asynchronous, I have done:

相关标签:
3条回答
  • 2020-11-27 20:33

    I know this is old but I've got to add this,
    the pipeTo is the right way but you don't need to copy your sender,
    you're already in the same context.
    actually the pipeTo does this for you.
    it will take the current sender ref (by passing to it's argument)
    and use it to resolve the future for you (look at it's implementation)
    just do:

    future {
      val ans = searchAndCache(s)
      println("Input Request: "+s+" output:"+ans+" "+reply.path)
      ans
    } pipeTo reply
    
    0 讨论(0)
  • 2020-11-27 20:43
    import akka.pattern.pipe
    

    Does the trick. Doing:

    val reply = sender
    future {
      val ans = searchAndCache(s)
      println("Input Request: "+s+" output:"+ans+" "+reply.path)
      ans
    } pipeTo reply
    

    replies back to the sender

    0 讨论(0)
  • 2020-11-27 20:58

    You are making a very common mistake of "closing over mutable state". The closure you pass to onComplete does not make a copy of this.sender, so when your onComplete gets called, you are sending the message to whatever this.sender happens to point to at that time, not what it pointed to when you created the closure.

    You can avoid this problem by creating your own local, immutable copy of the current contents of this.sender, and reference that value in the closure:

    val origSender = sender
    f.onComplete {
        case Successs(x) => origSender ! x
        ...
    }
    
    0 讨论(0)
提交回复
热议问题