Kotlin Coroutines the right way in Android

前端 未结 9 1115
醉酒成梦
醉酒成梦 2020-12-02 06:51

I\'m trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this

9条回答
  •  被撕碎了的回忆
    2020-12-02 07:00

    Like sdeff said, if you use the UI context, the code inside that coroutine will run on UI thread by default. And, if you need to run an instruction on another thread you can use run(CommonPool) {}

    Furthermore, if you don't need to return nothing from the method, you can use the function launch(UI) instead of async(UI) (the former will return a Job and the latter a Deferred).

    An example could be:

    fun loadListOfMediaInAsync() = launch(UI) {
        try {
            withContext(CommonPool) { //The coroutine is suspended until run() ends
                adapter.listOfMediaItems.addAll(resources.getAllTracks()) 
            }
            adapter.notifyDataSetChanged()
        } catch(e: Exception) {
            e.printStackTrace()
        } catch(o: OutOfMemoryError) {
            o.printStackTrace()
        } finally {
            progress.dismiss()
        }
    }
    

    If you need more help I recommend you to read the main guide of kotlinx.coroutines and, in addition, the guide of coroutines + UI

提交回复
热议问题