https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

Gopal S Akshintala

04/19/2020, 3:14 PM
How to achieve scatter-gatter or divide-conquer pattern with Coroutines? I am trying to achieve the below code, where I used ForkJoinPool to recursively divide list and join the results back. Please find a sample code below
Copy code
internal class MyRecursiveTask(private val names: List<String?>) : RecursiveTask<String>() {
    override fun compute(): String = if (names.size > MIN_LIST_SIZE) {
        val mid = names.size / 2
        val myRecursiveTask1 = MyRecursiveTask(names.subList(0, mid))
        val myRecursiveTask2 = MyRecursiveTask(names.subList(mid, names.size))
        myRecursiveTask1.fork()
        myRecursiveTask2.fork()
        val results = ArrayList<String>()
        results.add(myRecursiveTask1.join())
        results.add(myRecursiveTask2.join())
        concat(results) // This just concats strings
    } else {
        concat(names) // This just concats strings
    }

    companion object {
        private const val serialVersionUID = -5978274303314688527L
        private const val MIN_LIST_SIZE = 2 // In real-world, DO NOT have it below 10,000
    }
}
d

Dominaezzz

04/19/2020, 3:44 PM
one sec. (Just so I don't race with someone else)
Here you go.
Copy code
suspend fun recursiveTask(names: List<String?>): String {
    val MIN_LIST_SIZE = 2 // In real-world, DO NOT have it below 10,000

    return if (names.size > MIN_LIST_SIZE) {
        val mid = names.size / 2

        val results = coroutineScope {
            val leftTask = async { recursiveTask(names.subList(0, mid)) }
            val rightTask = async { recursiveTask(names.subList(mid, names.size)) }
            listOf(leftTask.await(), rightTask.await())
        }
        concat(results) // This just concats strings
    } else {
        concat(names) // This just concats strings
    }
}
👍 1
You would invoke like this.
Copy code
val actualResult = runBlocking(Dispatchers.Default) {
    recursiveTask(TEAM)
}
g

Gopal S Akshintala

04/21/2020, 4:28 AM
Thanks @Dominaezzz
8 Views