Updating the UI on changes

Now we only need to connect the UI to this channel. Let's go to the activity SearchActivity and add a function to monitor the channel and update the UI on changes:

private suspend fun updateCounter() {
val notifications = ResultsCounter.getNotificationChannel()
val results = findViewById<TextView>(R.id.results)

while (!notifications.isClosedForReceive) {
val newAmount = notifications.receive()

withContext(UI) {
results.text = "Results: $newAmount"
}
}
}

This code is simply getting the channel from the singleton and entering a loop for as long as the channel is open. Upon receipt of a new amount, it will simply set the new value to the TextView on the UI thread. Finally, we need to update onCreate() to make sure that it calls updateCounter(), as follows:

override fun onCreate(savedInstanceState: Bundle?) {
...

launch {
updateCounter()
}
}
..................Content has been hidden....................

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