Although others have pointed out that, in this case, the library provides its own method to post an operation to the main thread, coroutines provide a general solution that works regardless of a given library's functionality.
The first step is to stop using GlobalScope
for background jobs, doing this will lead to leaks where your activity, or scheduled job, or whatever unit of work you invoke this from, may get destroyed, and yet your job will continue in the background and even submit its results to the main thread. Here's what the official documentation on GlobalScope
states:
Application code usually should use application-defined CoroutineScope, using async or launch on the instance of GlobalScope is highly discouraged.
You should define your own coroutine scope and its coroutineContext
property should contain Dispatchers.Main
as the dispatcher. Furthermore, the whole pattern of launching jobs within a function call and returning LiveData
(which is basically another kind of Future
), isn't the most convenient way to use coroutines. Instead you should have
suspend fun getAddresses() = withContext(Dispatchers.Default) { getAddressList() }
and at the call site you should launch
a coroutine, within which you can now freely call getAddresses()
as if it was a blocking method and get the addresses directly as a return value.