I'm trying to implement a request -> response layer on top of websockets in Java. I recently stumbled across RxJava
, which seems like a nice library to use for this. Down below is my current approach for handling the request response flow (unimportant code omitted for readability)
public class SimpleServer extends WebSocketServer {
Gson gson = new Gson();
Map<String, Function<JsonObject, Void>> requests = new HashMap<>();
private static int count = 0;
public SimpleServer(InetSocketAddress address) {
super(address);
}
@Override
public void onMessage(WebSocket conn, String message) {
String type = ...;
JsonObject payload = ...;
if (type.equals("response")) {
Request request = requests.get(requestId).apply(payload);
}
}
public Single<JsonObject> request(String action) {
requests.put(Integer.toString(count++), response -> {
source.onSuccess(response);
return null;
});
broadcast(...);
}
}
Is this a viable solution or is there a better way?
I was thinking if there was a way to use RxJava
for both ways, i.e. the request would listen to an "onMessage" observable or something along those lines.
All help will be greatly appreciated.