Kotlin Coroutines with returning value

前端 未结 6 888
盖世英雄少女心
盖世英雄少女心 2020-12-17 08:54

I want to create a coroutine method which has returning value.

For example)

fun funA() = async(CommonPool) {
    return 1
}

fun funB() = async(Commo         


        
6条回答
  •  难免孤独
    2020-12-17 08:57

    It may be late to answer this question but hopefully someone will find it useful. The code snippet below calculates sum of 3 values A + B + C. Each value is calculated independently in its own background thread in parallel and then all interim results consolidated into one final result and returned to the main thread to display it on a screen.

    So it takes 5 seconds to calculate the final value (not 10 seconds = 2 + 3 + 5) and the result is 6 obviously and it's non-blocking, the main thread can handle other events while sum() execution is not complete.

    suspend fun sum(scheduler: ThreadPoolExecutor): Int = coroutineScope {
    
        withContext(scheduler.asCoroutineDispatcher()) {
            val a = async { funA() }
            val b = async { funB() }
            val c = async { funC() }
    
            a.await() + b.await() + c.await()
        }
    }
    
    fun funA(): Int {
        Thread.sleep(2000L)
        return 1
    }
    
    fun funB(): Int {
        Thread.sleep(3000L)
        return 2
    }
    
    fun funC(): Int {
        Thread.sleep(5000L)
        return 3
    }
    
    class MainActivity : AppCompatActivity(), View.OnClickListener {
        private val tripletsPool = ThreadPoolExecutor(3, 3, 5L, TimeUnit.SECONDS, LinkedBlockingQueue())
    
       ...
    
        override fun onClick(view: View?) {
            if (view == null) {
                return
            }
    
            when (view.id) {
                R.id.calculate -> {
                    GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) {
                        progressBar.visibility = View.VISIBLE
                        result.setText("${sum(tripletsPool)}")
                        progressBar.visibility = View.GONE
                    }
                }
            }
        }
    }
    

提交回复
热议问题