Efficiently Download Movies While Watching Others Using Isolates

ยท

2 min read

This article illustrates a real-world scenario with an Isolate where downloading and watching a movie might occur at the same time. The downloading will be handled on a separate thread (with an Isolate) while the watching will take place on the main thread.

Quick recap: I've given a simple explanation and illustration of how to use an Isolate if you wondering what isolates are. You can check here https://learnwithtunde.hashnode.dev/handle-expensive-or-long-running-tasks-with-an-isolate-to-prevent-an-app-from-freezing.

Output: You can check the output by clicking on the link below

The dependencies used are:

Dependencies
  dio: ^5.3.3
  video_player: ^2.7.2
  fluttertoast: ^8.2.2
  get_it: ^7.6.4
  path_provider: ^2.1.1

Note: If you want to run the code on Android Simulator, don't forget to add this below to the file located at <project root>/android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Code A: Here, a ReceivePort has been created and it is ready to start listening to messages from its corresponding SendPort (the listening happens on the main thread), and also keeping track of the progress and error response from the download.

Code B: Here, the download method from the video downloader needs some params, which are :

  • Dio:- It is used to make network calls.

  • SendPort:- It is used to send messages from another thread to its corresponding ReceivePort on the main thread.

  • DownloadUrl:- The video url.

  • Path:- The path on the phone to save the downloaded movie.

Code C: Here is where the magic happens. An Isolate.spawn will create a separate thread and perform the download on the separate thread.

Code D: The download method from the Dio will be called on the separate thread created by Isolate.spawn and Sendport will keep sending messages from this thread to its corresponding ReceivePort on the main thread.

Code D

Source code: Check the full implementation by clicking on the link below.

https://github.com/Abdullah8888/handle_download_with_isolate

Flutter documentation on isolate: check https://dart.dev/language/concurrency and https://api.flutter.dev/flutter/dart-isolate/Isolate-class.html

Thanks for reading. ๐Ÿ‘ ๐Ÿ˜Š

ย