java - How to make a runnable where the run code is able to access a variable provided in the trigger -
i have class listening websocket , when message received, should execute code depending on message type. throughout application want able register more listeners.
i created following messagelistener class:
static class messagelistener { private string triggermessage; private runnable runnable; messagelistener(string message, runnable runnable) { this.triggermessage = message; this.runnable = runnable; } private void trigger(string message) { if (message.equals(triggermessage)) { runnable.run(); } } }
i add listener this:
ws.setlistener(new ipdwebsocket.messagelistener("disconnect", new runnable() { @override public void run() { log.e("xx", "received message: "); } } ) );
when message received trigger listeners this:
for (int nr=0; nr < listeners.size(); nr++) { listeners.get(nr).trigger(msg); }
now problem in runnable able use message variable. this:
ws.setlistener(new ipdwebsocket.messagelistener("disconnect", new runnable() { @override public void run() { log.e("xx", "received message: " + message); } } ) );
but variable "message" isn't defined anywhere. idea's on how implemented? heaps!
instead of using runnable can use own interface
achieve scenario,
ex create 1 interface inside messagelistener
static class messagelistener { private string triggermessage; private messagetriggerlistener runnable; public interface messagetriggerlistener { public void onmessagereceived(string message); } messagelistener(string message, messagetriggerlistener runnable) { this.triggermessage = message; this.runnable = runnable; } private void trigger(string message) { if (message.equals(triggermessage)) { runnable.onmessagereceived(message); } } }
and can implement listener this,
ws.setlistener(new ipdwebsocket.messagelistener("disconnect", new messagelistener.messagetriggerlistener() { @override public void onmessagereceived(string message) { log.e("xx", "received message: " + message); } } ) );
wiki
Comments
Post a Comment