Adding a channel so that the UI reacts to updates

To make the implementation more interesting, let's make it so that the UI can listen to increments in the counter – and update the label – by subscribing to a channel. First, let's add a channel property to ResultsCounter:

object ResultsCounter {
private val context = newSingleThreadContext("counter")
private var counter = 0
private val notifications = Channel<Int>(Channel.CONFLATED)
...
}
We are making this channel private so that we can retrieve it as a ReceiveChannel, preventing the clients of the API from trying to send messages using it. We are making the channel conflated because we don't care if some notifications are lost: the UI only cares about the most recent value for the counter.

Notice that the channel is of type Int; this will allow us to simply send the new value on each change. Now let's add a function to expose the channel to the UI:

fun getNotificationChannel() : ReceiveChannel<Int> = notifications
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.122