Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Merge or skip duplicate messages in a Scala Actor?

Tags:

scala

actor

Let's say you have a gui component and 10 threads all tell it to repaint at sufficiently the same time as they all arrive before a single paint operation takes place. Instead of naively wasting resources repainting 10 times, just merge/ignore all but the last one and repaint once (or more likely, twice--once for the first, and once for the last). My understanding is that the Swing repaint manager does this.

Is there a way to accomplish this same type of behavior in a Scala Actor? Is there a way to look at the queue and merge messages, or ignore all but the last of a certain type or something?

like image 405
mentics Avatar asked Oct 11 '22 04:10

mentics


1 Answers

Something like this?:

act = 
  loop { 
    react {
      case Repaint(a, b) => if (lastRepaint + minInterval < System.currentTimeMillis) {
          lastRepaint = System.currentTimeMillis
          repaint(a, b)
    }
  }

If you want to repaint whenever the actor's thread gets a chance, but no more, then: (UPDATE: repainting using the last message arguments)

act =
  loop {
    react {
      case r@Repaint(_, _) =>  
        var lastMsg = r
        def findLast: Unit = {
          reactWithin(0) {
            case r@Repaint(_, _) => 
              lastMsg = r
            case TIMEOUT => repaint(lastMsg.a, lastMsg.b)
          }
        }
        findLast
    }
  }
like image 121
IttayD Avatar answered Oct 14 '22 04:10

IttayD