Junior — Middle
How to implement parallel execution of multiple network requests and combine their responses into a single container using multithreading?
sobes.tech AI
Answer from AI
To perform multiple network requests in parallel in Android, you can use multithreading with ExecutorService or libraries like RxJava or Kotlin Coroutines.
Example using ExecutorService and Future:
ExecutorService executor = Executors.newFixedThreadPool(3);
Callable<String> request1 = () -> performNetworkRequest(url1);
Callable<String> request2 = () -> performNetworkRequest(url2);
Callable<String> request3 = () -> performNetworkRequest(url3);
List<Callable<String>> tasks = Arrays.asList(request1, request2, request3);
try {
List<Future<String>> futures = executor.invokeAll(tasks);
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
results.add(future.get()); // Get the result of each request
}
// results contains responses of all requests
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
Thus, each request runs in a separate thread, and the results are collected into a list after all tasks are completed.
If using Kotlin, it is more convenient to use coroutines with async and awaitAll for parallel execution and combining results.