Using coroutine channels and the livedata builder together

Viewed 471

How might I use coroutine channels together with the livedata coroutine builder (androidx.lifecycle:lifecycle-livedata-ktx architecture component) to continuously listen for messages produced from a websocket library to a ReceiveChannel<String>?

My first thought is to implement it like this

val user: LiveData<String> = liveData {
    while(true) {
        val data = myWebsocketChannel.receive() //Channel suspend function
        emit(data)
    }
}

But this feels a bit "non-kotliny" and my gut is telling me that there is a better of solving this. Is there a better way of handling posting data once received from a coroutine channel?

1 Answers

I would write it like this:

val user: LiveData<User> = liveData {
    myWebsocketChannel.consumeEach { data ->
       emit(data)
   }
}

myWebsocketChannel.consumeEach { ... } is going to iterate forever (suspending, if channel is empty) until someone closes the myWebsocketChannel. On the producer side - where we are listening to the socket, we should be careful to not close channel prematurely.

Hope it helps :)

Related