Return a String inside the companion object function inside the CoroutineScope

In the MainActivity in have a companion object function which consumes the variable outside the function. In the functioni would like to return the data as string inside the CoroutineScope. Here is the code:-

class MainActivity : AppCompatActivity() {
private var data = “myName”

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val data = getMyOuterValue()
    Toast.makeText(this@MainActivity, data, Toast.LENGTH_SHORT).show()
}
init {
    instance = this
}
companion object {
    private var instance: MainActivity? = null
    fun getMyOuterValue() : String = CoroutineScope(Main).launch {
        instance?.data.toString()
    }.toString()
}

}

Note inside the function “getMyOuterValue” i would like to return the string but it returns the CoroutineScope object. Kindly assist

Short answer: you can’t. Whatever you do, you can’t wait directly inside onCreate() without blocking the UI. Instead, put launch() inside onCreate():

setContentView(R.layout.activity_main)
lifecycleScope.launch {
    val data = instance?.data.toString()
    Toast.makeText(this@MainActivity, data, Toast.LENGTH_SHORT).show()
}

Anyway, why do you use launch() in the first place? It doesn’t seem to do anything. Also, storing activity statically probably isn’t a good idea, although I may be wrong here.

The suspense function should not be used on the getMyOuterValue function but rather returns the string
@broot

1 Like

I’m not sure what do you mean. If you want to return a value from getMyOuterValue() then just do it normally, without launch():

fun getMyOuterValue() : String = instance?.data.toString()

You can’t at the same time run the operation in the background (launch()) and in the foreground (return directly). These are two mutually exclusive ways to do things.

As said earlier, it would be easier if you explain why do you use launch() here, because right now it seems not needed.

1 Like

Hey @broot if i do that way directly the app is crashing with error that i cant invoke the data outside the companion object in main thread.

What is the exact error message/stacktrace?

You have a mistake in understanding coroutine.
The Coroutine Scope is not a function that can return the value of a calculation, it`s just an executes algorithm.
If you want to read the data, make a var before the coroutine and store the value in this variable in the coroutine.

1 Like

Another reason it returns a CoroutineScope object is to manipulate the async task, for example, by canceling a network request

searchJob = CoroutineScope(Dispatchers.Main).launch { }

searchJob?.cancel()