Key value coding and observing is something that other languages do well, like objective-c for instance. What's the best way to achieve something similar in Mathematica (if at all possible)? That is, how can you trigger an event based on a certain variable's value changing without relying on front-end dynamics...

  • $\begingroup$ One idea would be to not use CompoundExpression in your programs, but, say, AngleBracket and do something like Unprotect[AngleBracket]; Precedence[AngleBracket] = 10.; SetAttributes[AngleBracket, HoldAll]; and then define AngleBracket[expr1_, expr2_, expri___] in such a way that after each evaluation of an argument a list of KVO pure function triggers would be checked. You could also add quite effective debugging this way I guess. Sorry to not work this out more, but time is short these days ... $\endgroup$ Nov 17, 2014 at 19:37
  • $\begingroup$ Hmm, interesting idea Rolf! thanks... it seems that TrackedSymbol sort of does kvo under the hood, but it too opaque and only works with Dynamics, actually the answer is quite simple $\endgroup$
    – user5601
    Nov 17, 2014 at 20:39
  • $\begingroup$ @LeonidShifrin The observer design pattern question you referenced is a great resource, my desire is simply to execute pre and post update blocks... $\endgroup$
    – user5601
    Nov 17, 2014 at 21:25

1 Answer 1


Here's a simplistic way to do what I needed, that is, running some code before and after the variable updates:

    ClearAll[kvo, r];
    SetAttributes[kvo, {HoldAll}];
    kvo[v_, pre_, post_] := ((v /: Set[v, x_] := (pre[v]; v := x; post[x])))

    kvo[r, Print["before update, var = ", #] &, 
     Print["after update, var = ", #, "\n"] &]
    Do[r = i^2, {i, 3}]


before update, var = r
after update, var = 1

before update, var = 1
after update, var = 4

before update, var = 4
after update, var = 9

Thanks @leonid for the link, very helpful, but that solution is a bit overkill for my needs....


Not the answer you're looking for? Browse other questions tagged or ask your own question.