WebSocket and Rx Java

2.6k views Asked by At

I'm develop an android app that communicates with the server using a protocol WebSocket. I use AsyncAndroid lib. WebSocket has listener, that receive data from server.

Something like this

private WebSocket.StringCallback mStringCallback = new WebSocket.StringCallback() {
        @Override
        public void onStringAvailable(String s) {

        }
    };

I need write api this, and i want use rxjava. But i cannot imagine, that should be Observable, and that Observer. i tried to do Observable string received from server into WebSocket listener, but i think it is bad idea. Are there any ideas how correctly build api. Thank u.

1

There are 1 answers

0
ByteWelder On

You could wrap WebSocket into a new interface like this:

interface RxWebSocket {
    void send(byte[]); // send data
    Observable<String> stringObservable(); // receive string data
}

Then in a RxWebSocket implementation you can use PublishSubject with an internal WebSocket.StringCallback to publish the Strings.