2

I need to upload a list of images into a storage, but I don't want to upload and await for every single image after the other, because it takes quite some time. I would like to upload them simultaneously, like in different threads. There is a way to do achieve multithreading with standard dart async? Or should I use Isolates? Do you have some sample code?

Slaine06
  • 85
  • 2
  • 8

2 Answers2

1

You can use them in a single future

final results = await Future.wait([
  uploadFunction(image1)
  uploadFunction(image2)

]);

you can start uploading all images without waiting for the previous one to complete await will be returned once both uploads are completed

Nikhil Biju
  • 645
  • 7
  • 8
0

You can use Queue

Whats it will do it will hold your actions and you can do other task while uploading images

import 'package:dart_queue/dart_queue.dart';

main() async {
  final queue = Queue(parallel: 2);

  
  final result1 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));
  final result2 = await queue.add(()=>Future.delayed(Duration(milliseconds: 10)));

  //Thats it!
}

By using this you dont need to add await.

NOTE: Make sure app is running while this queue is active.

Priyesh
  • 1,266
  • 5
  • 17
  • It seems that this library just allows me to queue futures and execute them one after the other, it does not execute them simultaneously. Am I wrong? – Slaine06 May 15 '21 at 07:01
  • Yes you are right but for the image uploading, i suggest you to use it to avoid await. – Priyesh May 15 '21 at 07:04
  • Sorry but I don't think this can help me. I need to await for the upload, but I want to speed up the process by uploading simultaneously using different threads. – Slaine06 May 15 '21 at 07:30
  • Okay, Keep growing ! – Priyesh May 15 '21 at 07:44