Reputation: 307
I am new in flutter. I need to call 5 API network calls in a single screen. It is taking very long time while i am using Async/await. How can we execute it on separate threads parallelly using isolate or anything else like it?
Upvotes: 5
Views: 4897
Reputation: 343
You may use isolate for this purpose isolate is a sort of multi threading in dart. Isolate creates a new thread and execute operation on the new thread so that the load will be distributed. You cannot send variables as a data back and forth but use port to send messages.
Here is a simple example of isolate with an API call and sending data back to the main thread using port.
First lets create a function which will be the entrypoint of isolate:
static entryPoint(SendPort sendPort)async{
var response = await http.get('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita');
sendPort.send(response.body); //sending data back to main thread's function
}
Now lets create isolate:
static void callApi()async{
var recievePort = new ReceivePort(); //creating new port to listen data
await Isolate.spawn(entryPoint, recievePort.sendPort);//spawing/creating new thread as isolates.
recievePort.listen((message) { //listening data from isolate
print(message);
});
}
Upvotes: 7
Reputation: 3742
You can use dio
package and call multiple concurrent API requests, do check the documentation:
Package: https://pub.dev/packages/dio
Upvotes: 1