0

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.

2
  • combine it with live data so you can observe the changes without including callbacks Commented May 22, 2020 at 16:07
  • Let's assume that I can't use LiveData or ViewModels. Commented May 22, 2020 at 16:13

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks much for the input. But why does it not work if I simply pass the scope as a parameter into the function? Can it not be done that way as well? Or is the suspend modifier the only way?
In your code you are using runBlocking, that effectively blocks the UI thread until the operation completes. You must use a suspend function if you want to have the code run in the backgrond, using coroutines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.