简体   繁体   中英

How Can I Make a Function That Returns a Value From a Coroutine?

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM