Denis Jung
Denis Jung

Reputation: 175

How to run 3rd function after running two functions parallel with Kotlin Coroutine

I am trying to run 2 functions in parallel, and after that I wanna start 3rd function with the result from the first 2 functions.

I searched Google and StackOverflow and I tried below code.
But func2() was started after func1() was finished, not parallel.
The Log was as below.
Start func1 -> End func1 -> Start func2 -> End func2 -> 10 + 20 = 30

How can I run 2 functions in parallel?

    val TAG = "TagMainActivity"
    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifecycleScope.launch(dispatcher) {
            val job1 = async { func1() }
            val job2 = async { func2() }
            func3(job1.await(), job2.await())
        }
    }

    suspend fun func1(): Int {
        Log.d(TAG, "Start func1")
        Thread.sleep(3000)
        Log.d(TAG, "End func1")
        return 10
    }

    suspend fun func2(): Int {
        Log.d(TAG, "Start func2")
        Thread.sleep(3000)
        Log.d(TAG, "End func2")
        return 20
    }

    suspend fun func3(bmp1: Int, bmp2: Int) {
        Log.d(TAG, "$bmp1 + $bmp2 = ${bmp1 + bmp2}")
    }

Upvotes: -1

Views: 34

Answers (1)

k314159
k314159

Reputation: 11246

You are using the same single-thread dispatcher for both jobs, they can't run at the same time. SKV's answer gives you a way to do two jobs in parallel using a single thread.

Sometimes, it's impossible to avoid blocking calls - for example, if you have async jobs that do I/O. In this question, you can imagine Thread.sleep() as emulating such an unavoidable blocking call. Therefore, you should use a dispatcher other than a single-thread one so that you can call the two jobs from multiple threads. Dispatchers.IO would be a good choice for that. So, if you use Dispatchers.IO, you can keep the Thread.sleep() call:

Upvotes: 0

Related Questions