本文介绍了如何在协奏曲中使用协程,以便我的代码可以像同步一样编写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's an example from 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)
}
}

我如何利用协程,以便以这种方式编写代码:

How can I take advantage of coroutines so I can write my code in this manner:

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)
}

您应该按照以下说明实施您的活动: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-生命周期和协程-父子级结构

You should implement your activity like described here: 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()
    } 
}

这篇关于如何在协奏曲中使用协程,以便我的代码可以像同步一样编写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:48