gpt4 book ai didi

android - 如何将协程与 volley 一起使用,以便我的代码可以像同步一样编写?

转载 作者:行者123 更新时间:2023-12-05 00:46:49 26 4
gpt4 key购买 nike

这是来自 developer.android.com 的示例

class MainActivity : AppCompatActivity() {

lateinit var textView:TextView
lateinit var button:Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

textView = findViewById(R.id.textView)
button = findViewById(R.id.button)

button.setOnClickListener({
getData()
})
}

fun getData(){
val queue = Volley.newRequestQueue(this)
val url = "http://www.google.com/"

val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "Something went wrong!" })

queue.add(stringRequest)
}
}

如何利用协程,以便以这种方式编写代码:
val data = getData()
textView.text = data

最佳答案

您可以使用 suspendCoroutine ,见 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html

suspend fun getData() = suspendCoroutine<String> { cont ->
val queue = Volley.newRequestQueue(this)
val url = "http://www.google.com/"

val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
cont.resume("Response is: ${response.substring(0, 500)}")
},
Response.ErrorListener { cont.resume("Something went wrong!") })

queue.add(stringRequest)
}

您应该像这里描述的那样实现您的 Activity : https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy
class MainActivity: AppCompatActivity(), CoroutineScope {
protected lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
...
button.setOnClickListener({
launch {
val data = getData()
textView.text = data
}
})
}

override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}

关于android - 如何将协程与 volley 一起使用,以便我的代码可以像同步一样编写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com