I am trying to make my Mathematica function to serve as an event handler for the events generated by a Java object.
Specifically, I have a Java object that connects as a client to a server that periodically pushes updates to all clients. I also have an observer object that calls it's update
method whenever the client receives any updates.
My goal is to catch this updates inside Mathematica, and handle them with a Mathematica function
It appears that JLink has a way of doing this with ImplementJavaInterface
command http://reference.wolfram.com/mathematica/JLink/ref/ImplementJavaInterface.html.
Here is how I've used it:
(* create a client that connects to localhost:3000 *)
client = JavaNew["me.kutrumbos.DdpClient", "localhost", MakeJavaObject[3000]];
(* create an observer that monitors client's events *)
observer = JavaNew["me.kutrumbos.examples.ObservableDdpClientObserver"];
(* create a variable that will be updated with data from incoming events *)
collections = {};
(* define event handler that updates collections variable with the new value *)
onCollectionUpdate[msg_] := collections = observer@getJSONObjectsList["coll"];
(* add event handler to the observer *)
observer@addMessageHandler[
ImplementJavaInterface["me.kutrumbos.examples.MessageHandler",
"update" -> "onCollectionUpdate"]];
(* add observer to the client *)
client@addObserver[observer];
(* connect to the server *)
client@connect[];
When I run this inside a notebook, everything works. Every time an event occurs, collections
variable gets updated with the data contained in the event.
However, when I put this code in the package, and expose collections
by adding collections::usage = "global var"
in the preamble of the package, the variable doesn't update, and the event handler doesn't even seem to run.
I tried inserting MessageDialog["Event Handler alert"]
inside the event handler to see if the event handler is even called, and I am not getting any pop-up alerts when I generate new events on the server.
Any idea why this might be happening?
onCollectionUpdate
becomes something likeYourPackage`Private`onCollectionUpdate
, and this may be the source of trouble. So, you need to use now"update" -> "`YourPackage`Private`onCollectionUpdate"
, or whatever the long name for this symbol becomes inside a package. $\endgroup$JLink
, which I assumed you did in your package either using second argument ofBeginPackage
, or usingNeeds["JLink`"]
in the implementation section. $\endgroup$