NetworkServiceDiscovery thread

from the CommonsWare Community archives

At April 27, 2021, 7:51pm, Jan asked:

I have a network service discovery resolver listener. When it gets the service info, I need to update the UI.
But because the callback for resolver listener is on a different thread, I get IllegalStateException saying I can’t update on a background thread (tried updating UI and also tried just setting a LiveData value in a runnable).

Should I do a launch on Main thread? Or is there another way to get the data from Network Service Discovery callback over to my viewModel to update the UI? I already pass in a lambda and that works but the lambda can’t do any of the above because it is also running on a background thread.


At April 27, 2021, 8:06pm, Jan replied:

Much to my surprise, adding in the viewModelScope.launch() and putting the code there - worked!


At April 27, 2021, 10:31pm, mmurphy replied:

The default dispatcher for viewModelScope.launch() is Dispatchers.Main. As a result, the code in that coroutine will be run on the main application thread, other than any portions that switch to another dispatcher (e.g., via withContext()).

Anyway, I’m glad that you got it working!