I am creating a networking application in Mathematica that runs a non-stop simulation, and periodically receives new information from the remote server that affects the simulation.

Whenever values of certain variables inside the simulation change, Mathematica needs to send an update with the values to the remote server.

Is there a way to catch an event in Mathematica that corresponds to the change in the value of a specific variable?

For example, assume that initially I have two variables: a and b, such that a=1, and b=1. Then, throughout the simulation one of the variables changes, while the second one remains the same: a=2, b=1. Is it possible to write an event handler that knows which variable has changed and what the new value is?

I've seen this discussion: Triggering actions when a variable is set, that recommends using upvalues for Set and SetDelayed: $var /: Set[$var, value_] := Block[{$in = True}, Print["$var set to ", value]; $var = value] /; Not@TrueQ[$in]

But this seems to not cover all possible cases when a variable might change, and requires defining UpValues for every variable.

Is there a better way?

  • $\begingroup$ Not an answer in any way but just curious - how does your simulation communicate with the remote server? $\endgroup$ Jun 21, 2013 at 1:51
  • $\begingroup$ @VincentTjeng, I have a Java object that periodically receives updates from the remote server through a websocket. When that happens it calls one of its methods, for which I created my own event handler in Mathematica using ImplementJavaInterface[]. This event handler basically assigns new values to variables that are used inside the simulation, and thus affects the simulation. I pasted some of the code in my previous question here: mathematica.stackexchange.com/questions/27330/… $\endgroup$
    – verse
    Jun 21, 2013 at 15:12
  • 1
    $\begingroup$ It might be possible by using by using java bean property change listeners. Please see the part with 'Using JavaBeans' reference.wolfram.com/mathematica/JLink/tutorial/… especially the part with MathPropertyChangeListener and MathListener. $\endgroup$
    – s.s.o
    Jun 21, 2013 at 20:38
  • $\begingroup$ The better way is to use Internal`ValueChangeVeto and Internal`AddHandler["VetoableValueChange", myVetoFunction] as mentioned by Leonid in the other thread. Unfortunately, the operation of these is not fully understood, and it is not clear if these can be used with ownvalues. Regardless of that, this question is still a duplicate of the other one. $\endgroup$ Sep 26, 2015 at 17:24


Browse other questions tagged or ask your own question.