Reputation: 121
I just can't figure out how to remove listener when I have some event executed. I have some leaking issue using websockets, and this can probaly fix it.
final WebSocket w = asyncHttpClient.prepareGet(url)
.execute(new WebSocketUpgradeHandler.Builder().build())
.get();
w.addWebSocketListener(new WebSocketTextListener() {
public void onMessage(String message) {
listener.onMessage(responseMessage);
// Here is the place I want to do my w.removeWebSocketListener(l);
}
@Override
public void onFragment(String s, boolean b) {
}
public void onOpen(WebSocket websocket) {
}
@Override
public void onClose(WebSocket webSocket) {
}
@Override
public void onError(Throwable throwable) {
}
});
The problem is when I create WebSocketTextListener lis = new ....
and passing in there is something like one object need other object and other object is dependent on this, and I'm still now allowed to do what I want.
Looks like it is something simple, but can't figure out.
Upvotes: 0
Views: 1829
Reputation: 121
Using "this" in anonumous inner class is the way to solve problem. But, it is muck better to refactor code, to avoid using anonumous classes, for testability and better understanding.
Upvotes: 1
Reputation: 2710
Normally event listeners can be removed with a removeXXXListener
method. But it requires that you provide the exact same event listener instance as parameter. You can store the event listener and later remove it using the same reference. But since you, in the onMessage
message already are inside the scope of the event listener, using this
should work.
Try something like
listener.onMessage(responseMessage);
// Here is the place I want to do my w.removeWebSocketListener(l);
w.removeWebSocketListener(this);
Upvotes: 1