Reputation: 717
I want to write a function that will always be called on the UI/main thread. Within that function, it will fetch text on a background thread (needs to access something from a file on the device) and then return that text to the main thread. Can this be done using coroutines in an idiomatic way?
Here is what I have done so far, but I fear it will run on the main thread:
fun getDisplayableName(context: Context): String =
if(someCondition)
context.getString(R.string.someString)
else runBlocking{
var name String: String? = null
launch(Dispatchers.IO) {
name = // some background logic, where name may still be null
}
name ?: ""
}
I want to use this function in an Android activity:
@Override
fun onCreate() {
// Other logic
nameTextView.text = MyHelperClass.getDisplayableName(this)
}
I'm looking for similar behavior to handling asynchronous threading with callbacks, but obviously without the callbacks part.
For the sake of discussion, assume I can't use LiveData or ViewModels.
Upvotes: 0
Views: 603
Reputation: 29260
You need a suspend
function
suspend fun getDisplayableName(context: Context): String =
if(someCondition) {
context.getString(R.string.someString)
} else {
withContext(Dispatchers.IO) {
val name = // some background logic, where name may still be null
name.orEmpty()
}
}
}
You would call it like this from onCreate
lifecycleScope.launch {
val name = getDisplayableName(this)
}
Upvotes: 1