这是来自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
答案 0 :(得分:3)
您可以使用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)
}
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()
}
}