calmd
calmd

Reputation: 11

What is the proper way to return data from okhttp WebSocketListener?

I am trying to write an Android Chess client using websockets. I chose the okhttp3 library. I can make a successful connection and can send data and receive. However, I am not sure how to return the data to LiveData for the ViewModel. I am somewhat familiar with Kotlin coroutines but I am not sure how I would get the data out of the listener.

I have tried trying to return from the function but as it is an overridden function I cannot return from it.

Here is the current WebSocketListener:

class EchoWebSocketListener : WebSocketListener() {

    private val NORMAL_CLOSURE_STATUS = 1000

    override fun onOpen(webSocket: WebSocket, response: Response) {
        super.onOpen(webSocket, response)
        webSocket.send("Hello It is me")
        webSocket.send("test 3!")
    }

    override fun onMessage(webSocket: WebSocket, text: String){
        super.onMessage(webSocket, text)
        outputData("Receiving $text")
    }

    override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
        super.onMessage(webSocket, bytes)
        outputData("Receiving bytes : " + bytes.hex())

    }

    override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
        super.onClosing(webSocket, code, reason)
        outputData("$code $reason")
    }

    private fun outputData(outputString: String) {
        d("web socket", outputString)
    }
}

And here is the setup code in the repository

 fun startChat() {
        httpClient = OkHttpClient()
        val request = Request.Builder()
            .url("ws://echo.websocket.org")
            .build()

        val listener = EchoWebSocketListener()
        val webSocket = httpClient.newWebSocket(request, listener)
        //webSocket.
        httpClient.dispatcher.executorService.shutdown()
    }

I would like to be able to run the repository with a Kotlin coroutine and return LiveData for the fragment to consume.

Upvotes: 1

Views: 3389

Answers (1)

Ge3ng
Ge3ng

Reputation: 2430

In your EchoWebSocketistener you could create a private MutableLiveData like so

class EchoWebSocketListener : WebSocketListener() {

    private val _liveData = MutableLiveData<String>()
    val liveData: LiveData<String> get() = _liveData

    // Overridden methods

    private fun outputData(string: String) {
        _liveData.postValue(string)
    }

}

Then you return the live data from the listener like so in a Coroutine

fun startChat(): LiveData<String> {
    val listener = EchoWebSocketListener()
    GlobalScope.launch(Dispatchers.IO) {
        httpClient = OkHttpClient()
        val request = Request.Builder()
            .url("ws://echo.websocket.org")
            .build()


        val webSocket = httpClient.newWebSocket(request, listener)
        //webSocket.
        httpClient.dispatcher.executorService.shutdown()
    }
    return listener.liveData
}

Upvotes: 1

Related Questions