在 CoroutineScope 内的伴生对象函数中返回一个 String
在 MainActivity 中有一个伴随对象函数,它消耗函数外部的变量。在函数中,我想将数据作为 CoroutineScope 内的字符串返回。这是代码: -
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()
}
}
请注意,在函数“getMyOuterValue”中,我想返回字符串,但它返回 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这里,您尝试强制函数返回 String,而预期返回 Coroutine Job
并使用
.toString( )
以避免类型不匹配。无论此设置的目的是什么,如果您想从协程内部返回一个值;您可以使用
async
构建器来代替;这需要使用挂起函数来利用await()
方法。你的函数应该是:
并且作为一个挂起函数,对它的调用必须来自协程:
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 theawait()
method.Your function should be:
And as a suspend fun, the call to it must be from a coroutine:
问题是您没有正确返回它并且没有等待协程完成。 尝试这个
在 oncreate() 中
The problem is you are not returning it correctly and not waiting for the Coroutine to complete. try this
in oncreate()