Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

marked as duplicate by Oleksandr R., blochwave, Karsten 7., m_goldberg, Pickett Sep 26 '15 at 18:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Not an answer in any way but just curious - how does your simulation communicate with the remote server? – Vincent Tjeng Jun 21 '13 at 1:51
@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:… – verse Jun 21 '13 at 15:12
It might be possible by using by using java bean property change listeners. Please see the part with 'Using JavaBeans'… especially the part with MathPropertyChangeListener and MathListener. – s.s.o Jun 21 '13 at 20:38
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. – Oleksandr R. Sep 26 '15 at 17:24