Junior — Middle
How to implement a function that loads data from two different sources asynchronously at the same time?
sobes.tech AI
Answer from AI
For asynchronous data loading from two different sources in Android, Kotlin Coroutines can be used. This allows running two operations in parallel and waiting for their completion.
Example:
import kotlinx.coroutines.*
fun loadData() {
CoroutineScope(Dispatchers.IO).launch {
val deferred1 = async { loadFromSource1() }
val deferred2 = async { loadFromSource2() }
val result1 = deferred1.await()
val result2 = deferred2.await()
withContext(Dispatchers.Main) {
// Handling results on the main thread
println("Result 1: $result1")
println("Result 2: $result2")
}
}
}
suspend fun loadFromSource1(): String {
// Simulate data loading
delay(1000)
return "Data from source 1"
}
suspend fun loadFromSource2(): String {
// Simulate data loading
delay(1500)
return "Data from source 2"
}
In this example, two loading functions are run in parallel, and then the results are processed after their completion.