如何在协奏曲中使用协程,以便我的代码可以像同步一样编写?

时间:2018-11-26 17:19:46

标签: kotlin android-volley coroutine

这是来自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

1 个答案:

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

您应按照以下说明进行活动: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()
    } 
}