'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 function I 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



Solution 1:[1]

The problem is you are not returning it correctly and not waiting for the Coroutine to complete. try this

 fun getMyOuterValue() = CoroutineScope(Dispatchers.IO).async {
        return@async instance?.data.toString()

    }

in oncreate()

CoroutineScope(Dispatchers.IO).launch {
        val data = getMyOuterValue()
        data.await()

}

Solution 2:[2]

fun getMyOuterValue() : String = CoroutineScope(Main).launch

Here you try to force the function to return a String while it's expected to return a Coroutine Job

And you force that with .toString() to avoid type mismatch.

Regardless the purpose of this setup, if you want to return a value from inside a coroutine; you can use async builder instead; and this requires to use a suspend function to utilize the await() method.

Your function should be:

suspend fun getMyOuterValue() = CoroutineScope(Main).async {
    return@async instance?.data
}.await()

And as a suspend fun, the call to it must be from a coroutine:

CoroutineScope(Main).launch {
    val data = getMyOuterValue()
    Toast.makeText(this@MainActivity, data, Toast.LENGTH_SHORT).show()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vignesh
Solution 2 Zain