{"id":56777,"date":"2023-02-15T12:47:21","date_gmt":"2023-02-15T07:17:21","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=56777"},"modified":"2023-02-17T22:54:02","modified_gmt":"2023-02-17T17:24:02","slug":"isolates-in-flutter","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/isolates-in-flutter\/","title":{"rendered":"Isolates in Flutter"},"content":{"rendered":"<p>I have always wondered what set of code to run in the background to make my app powerful and responsive but I don\u2019t really know how. Some time back I got to know about isolates and I tried implementing it. And I should tell you, it was painful. But I recently discovered how easy it has become. So here it is.<\/p>\n<p>You might have heard about isolates but never really understood. Or maybe you might have implemented isolates but the code has always been messy and tedious to write. In any case, this blog will guide you through the ups and downs of the Isolate history and the current and better implementation. You might want to use the latest method or you might want to use the old method after all, all up to your use case.<\/p>\n<h2 id=\"4ef1\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">The basics<\/h2>\n<p>This is how <a class=\"ax agl\" href=\"https:\/\/api.flutter.dev\/flutter\/dart-isolate\/Isolate-class.html\" target=\"_blank\" rel=\"noopener ugc nofollow\">Flutter Documentation<\/a> defines Isolates:<\/p>\n<blockquote><p>An isolated Dart execution context.<\/p><\/blockquote>\n<p id=\"73a4\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Did you understand anything? At least I did not. So let\u2019s begin understanding Isolates and then we\u2019ll write our own definition. So what all do we need for Isolates Recipe?<\/p>\n<ol class=\"\">\n<li id=\"3c23\" class=\"agt agu yr rn b zy zz abb abc abe agv abi agw abm agx abq agy agz aha dz bx\" data-selectable-paragraph=\"\">What are Isolates?<\/li>\n<li id=\"57fe\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">Why do we need them?<\/li>\n<li id=\"bf34\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">What is Event Handling?<\/li>\n<li id=\"d2ab\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">How to implement Isolates?<\/li>\n<li id=\"6b1a\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">And finally, what are Isolate Groups?<\/li>\n<\/ol>\n<blockquote><p>We\u2019ll start with the bigger picture of Isolates and see what does it really mean and go deep down and piece all the parts together to see how each part of it works together so that we can understand what Isolates really do and why do we need them.<\/p><\/blockquote>\n<h2 id=\"15ce\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">What are Isolates?<\/h2>\n<p id=\"18a9\" class=\"pw-post-body-paragraph zw zx yr rn b zy agg ud aba abb agh ug abd abe agi abg abh abi agj abk abl abm agk abo abp abq ob bx\" data-selectable-paragraph=\"\">To really understand isolates, first we need to go further back and make sure we know the answer to these 2 questions:<\/p>\n<ol class=\"\">\n<li id=\"10c3\" class=\"agt agu yr rn b zy zz abb abc abe agv abi agw abm agx abq agy agz aha dz bx\" data-selectable-paragraph=\"\"><strong class=\"rn mq\">What is the difference between Processor Cores and Threads?<br \/>\n<\/strong>Core is a physical hardware component, whereas thread is the virtual component that manages the tasks of the core. Cores enable completion of more work simultaneously, while threads enhance computational speed and throughput. Cores use content switching, but threads use multiple processors for executing different processes.<\/li>\n<li id=\"b3b2\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\"><strong class=\"rn mq\">What is the difference between concurrent and parallel processing?<br \/>\n<\/strong>Concurrency is when two or more tasks can start, run, and complete in overlapping time periods. It doesn\u2019t necessarily mean they\u2019ll ever both be running at the same instant. For example, multitasking on a single-core machine. Parallelism is when tasks literally run at the same time, e.g., on a multicore processor.<\/li>\n<\/ol>\n<h2 id=\"4a74\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">Let\u2019s get back to Isolates.<\/h2>\n<p>Dart uses Isolate model for concurrency. Isolate is nothing but a wrapper around thread. But threads, by definition, can share memory which might be easy for the developer but makes code prone to race conditions and locks. Isolates on the other hand cannot share memory and instead rely on message passing mechanism to talk with each other. If anything is difficult to comprehend, keep reading. I am sure, you\u2019ll get it.<\/p>\n<p>Using isolates, Dart code can perform multiple independent tasks at once, using additional cores if they\u2019re available. Each Isolate has its own memory and a single thread running an event loop. We\u2019ll get to event loop in a minute.<\/p>\n<h2 id=\"2edd\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">Why do we need Isolates?<\/h2>\n<p id=\"b01c\" class=\"pw-post-body-paragraph zw zx yr rn b zy agg ud aba abb agh ug abd abe agi abg abh abi agj abk abl abm agk abo abp abq ob bx\">Before we get into more detail, we first need to understand how async-await really works.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-56767\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-300x143.png\" alt=\"\" width=\"298\" height=\"142\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-300x143.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-624x297.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM.png 677w\" sizes=\"(max-width: 298px) 100vw, 298px\" \/><\/p>\n<p>We want to read some data from a file and then decode that JSON and print the JSON Keys length. We don\u2019t need to go into the implementation details here but can take the help of the image below to understand how it works.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone wp-image-56768 size-large\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-1024x588.png\" alt=\"\" width=\"625\" height=\"359\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-1024x588.png 1024w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-300x172.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-768x441.png 768w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-1536x882.png 1536w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-2048x1176.png 2048w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-10-at-5.33.17-PM-624x358.png 624w\" sizes=\"(max-width: 625px) 100vw, 625px\" \/><\/p>\n<p>When we click on this button, <strong class=\"rn mq\">Place Bid<\/strong>, it sends a request to _readFileAsync, all of which is dart code that we wrote. But this function _readFileAsync, executes code using Dart Virtual Machine\/OS to perform the I\/O operation, which in itself is a different thread, the I\/O thread. This means, the code in the main function runs inside the main isolate. When the code reaches the _readFileAsync, it transfers the code execution to I\/O thread, and the Main Isolate waits until the code is completely executed or an error occurs. This is what await keyword does.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56769\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/basics-await-300x84.png\" alt=\"\" width=\"300\" height=\"84\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/basics-await-300x84.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/basics-await.png 541w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Now, once the contents of the files are read, the control returns to the primary isolate, and we start parsing the String data as JSON and print the number of keys. This is pretty straight forward. But let\u2019s suppose, the JSON parsing was a very big operation, considering a very huge JSON and we start manipulating the data to conform to our needs. Then this work is happening on the Main Isolate. At this point of time, the UI could hang, making our users fustrated.<\/p>\n<p>&nbsp;<\/p>\n<h2 id=\"2199\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">What is Event Handling?<\/h2>\n<p>As we discussed, Isolate is a wrapper around thread, and each Isolate has an event loop executing events. These events are nothing but what happens when we use the application. These events are added in a queue which then the Event loop takes in and processes. These events are processed in the first-in-first-out fashion. This image below is just an example.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56770\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-loop-300x55.png\" alt=\"Event Loop\" width=\"300\" height=\"55\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-loop-300x55.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-loop.png 511w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Let\u2019s use this code again for understanding event handlers. We already know what is happening in this block.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56767\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-300x143.png\" alt=\"\" width=\"300\" height=\"143\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-300x143.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM-624x297.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.32.57-AM.png 677w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56771\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-handling-300x151.png\" alt=\"\" width=\"300\" height=\"151\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-handling-300x151.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-handling.png 588w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p id=\"fe3f\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Our apps start and it draws the UI (Paint Event) is pushed on to the queue. We click on the <strong class=\"rn mq\">Place Bid<\/strong> button and and file handling code starts. So the Tap Event is pushed in the queue. After it is complete, let\u2019s suppose the UI is updated, so again the Paint Event is pushed in the queue.<\/p>\n<p id=\"281c\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Now because the our logic for handling the file and JSON was very small, the UI doesn\u2019t stutter or jank. But let\u2019s, for a while, imagine again that out code for handling file was huge and it takes a lot of time. Now the event queue and the event loop looks similar to this image below.<\/p>\n<p data-selectable-paragraph=\"\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56772\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-jank-267x300.png\" alt=\"Event Jank\" width=\"267\" height=\"300\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-jank-267x300.png 267w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/event-jank.png 378w\" sizes=\"(max-width: 267px) 100vw, 267px\" \/><\/p>\n<p data-selectable-paragraph=\"\">Now that the main isolate takes a lot of time to actually process that event, our animation or UI might hang and irritate your users, causing huge dropoffs. This is where spawning a new isolate or a worker Isolate comes in.<\/p>\n<h2 id=\"2b51\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">How to implement Isolates?<\/h2>\n<p id=\"b97a\" class=\"pw-post-body-paragraph zw zx yr rn b zy agg ud aba abb agh ug abd abe agi abg abh abi agj abk abl abm agk abo abp abq ob bx\" data-selectable-paragraph=\"\">All our dart code in the flutter app runs in isolate. Whether it is main isolate or a worker isolate is up to you. The main isolate is created for you and you don\u2019t have to do anything else here. The main function starts on the Main Isolate. Once we have our main function running, we can start spawning new isolates.<\/p>\n<p id=\"3c59\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">So there\u2019s 2 ways of implementing Isolates, the short and new method or the long and old method. We can use either depending upon the use case.<\/p>\n<p data-selectable-paragraph=\"\"><strong class=\"rn mq\">Let\u2019s start with the already existing method.<\/strong><\/p>\n<p id=\"b567\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">As we had already discussed, Isolates, unlike threads, don\u2019t share memory. This is done so as to prevent race conditions and locks. But the communication between Isolates is done using message passing. These messages are primitives and you can check out the whole list of objects that can be passed between isolates <a class=\"ax agl\" href=\"https:\/\/api.dart.dev\/stable\/2.19.2\/dart-isolate\/SendPort\/send.html\" target=\"_blank\" rel=\"noopener ugc nofollow\">here<\/a>.<\/p>\n<p id=\"165c\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">To pass messages, Dart provides us with Ports. SendPort and ReceivePort.<\/p>\n<p id=\"e976\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Since we\u2019re discussing the old method for spawning Isolates, we need to know that isolate methods need to be top-level or static functions.<\/p>\n<p id=\"e44d\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Here is the <a class=\"ax agl\" href=\"https:\/\/github.com\/DhruvamSharma\/NFT-Material3\" target=\"_blank\" rel=\"noopener ugc nofollow\">link<\/a> to the code if you want to follow along.<\/p>\n<p data-selectable-paragraph=\"\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56773\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.40.24-AM-300x134.png\" alt=\"\" width=\"300\" height=\"134\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.40.24-AM-300x134.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.40.24-AM-624x278.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.40.24-AM.png 674w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p id=\"6701\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">What does this code do:<\/p>\n<ol class=\"\">\n<li id=\"be66\" class=\"agt agu yr rn b zy zz abb abc abe agv abi agw abm agx abq agy agz aha dz bx\" data-selectable-paragraph=\"\">Here we create an instance of RecievePort to receive data. Remember this is the old method for spawning Isolates. It can be a little long but it is necessary to know the details.<\/li>\n<li id=\"335c\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">We create a Worker Isolate on the Main Isolate using Isolate.spawn and pass down a top-level function that runs the blocking code. We also pass down a list of arguments, the first one, SendPort which will be used to send the data from the worker Isolate, and the second is the download link. We wait till the new Isolate has been spawned.<\/li>\n<li id=\"e181\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">We then wait for the result, which is some form of a String and use it however we want. This data can be anything from <a class=\"ax agl\" href=\"https:\/\/api.dart.dev\/stable\/2.19.2\/dart-isolate\/SendPort\/send.html\" target=\"_blank\" rel=\"noopener ugc nofollow\">this<\/a> list of object.<\/li>\n<li id=\"dd4d\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">ResultPort.first uses a stream subscription behind the screen and waits for the data from the worker isolate to be pushed onto it. As soon as the first item arrives, we return the result.<\/li>\n<\/ol>\n<p>This is the _readAndParseJson function that receives the argument and runs the worker isolate code. This is a dummy function that does nothing but delays the control for 2 seconds and then exits. The exit function terminates the current isolate synchronously. Certain checks are performed before sending the data back to the calling isolate and the data is sent back using the SendPort.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56774\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.41.54-AM-300x160.png\" alt=\"\" width=\"300\" height=\"160\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.41.54-AM-300x160.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.41.54-AM-624x334.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.41.54-AM.png 630w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Although this functions correctly but we have not handled any errors which can be thrown from the worker isolate or any error which can occur while spawning a new isolate.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56775\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.42.43-AM-225x300.png\" alt=\"\" width=\"225\" height=\"300\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.42.43-AM-225x300.png 225w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.42.43-AM-624x831.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.42.43-AM.png 636w\" sizes=\"(max-width: 225px) 100vw, 225px\" \/><\/p>\n<p id=\"c70a\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Everything is pretty same here, we just have added error handling here.<\/p>\n<p id=\"42f6\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">What this code does is:<\/p>\n<ol class=\"\">\n<li id=\"009f\" class=\"agt agu yr rn b zy zz abb abc abe agv abi agw abm agx abq agy agz aha dz bx\" data-selectable-paragraph=\"\">We add errorsAreFatal to true while spawning a new isolate to make sure that the Main Isolate is aware of any errors. We assign the SendPort for onExit and onError handlers to make sure that if any errors that occur during exiting or spawning.<\/li>\n<li id=\"3153\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">We also add a try-catch block while spawning a new isolate to make sure that if any error occurs during spawning, we catch that and stop this operation, altogether.<\/li>\n<li id=\"bd83\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">If the spawning is successful and some data do come from the worker isolate, we need to check if it\u2019s error or not.<\/li>\n<li id=\"6624\" class=\"agt agu yr rn b zy ahb abb ahc abe ahd abi ahe abm ahf abq agy agz aha dz bx\" data-selectable-paragraph=\"\">If the message sent back is null, this means the isolate exited without any message, and an error has occurred. If the response is a list, this means the worker Isolate has sent back an error and a stacktrace. Else this is a successful transaction.<\/li>\n<\/ol>\n<p>This does seem like an overkill if we wanted to do just one-off message passing. One message and close the Isolate. Everytime you wanted to spawn a new isolate you\u2019ll have to write the same code again. Since the Isolate logic is pretty custom. Every time you might want to pass in some different arguments and it would be very tedious. This is why a new method was devised for one-off transactions.<\/p>\n<p><strong class=\"rn mq\">The new method: Isolate.run<\/strong><\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-medium wp-image-56776\" src=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.45.36-AM-300x114.png\" alt=\"\" width=\"300\" height=\"114\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.45.36-AM-300x114.png 300w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.45.36-AM-624x238.png 624w, \/blog\/wp-ttn-blog\/uploads\/2023\/02\/Screenshot-2023-02-16-at-11.45.36-AM.png 627w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p id=\"1b62\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">This is all there is for the new method.<\/p>\n<p id=\"f3ff\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">We spawn a new Isolate using the run method which abstracts out all the granular details and the error handling and saving you a lot of time. This helps in spawning, error handling, message passing and terminating the Isolate all using these few little lines of code.<\/p>\n<blockquote class=\"aht\">\n<p id=\"ed1b\" class=\"ahu ahv yr bu ahw ahx ahy ahz aia aib aic abq hj\" data-selectable-paragraph=\"\">One thing to note here is that the function _readAndParseJsonWithoutIsolateLogic, does not contain any custom logic for the Isolate. No ports, no arguments.<\/p>\n<\/blockquote>\n<h2 id=\"e78d\" class=\"afv afw yr bu yb qn aid qo qr qs aie qt qw abe aif aga rb abi aig agc rg abm aih age rl agf bx\" data-selectable-paragraph=\"\">When to use the new Run method and when to use the old spawn method?<\/h2>\n<p id=\"26f0\" class=\"pw-post-body-paragraph zw zx yr rn b zy agg ud aba abb agh ug abd abe agi abg abh abi agj abk abl abm agk abo abp abq ob bx\" data-selectable-paragraph=\"\">These examples above shows message passing that happens only 1 time. So run method should be used. It greatly reduces the code lines and test cases.<\/p>\n<p id=\"b4a7\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">But if you want to create something that needs multiple messages to be passed between the Isolates, we need to use the old <strong class=\"rn mq\">Isolate.spawn() <\/strong>method. An example of this could be when you start downloading a file on a worker isolate and want to show the progress of the download on the UI. This means the progress count needs to be passed again and again.<\/p>\n<p id=\"8e29\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">With this, we need to implement the whole SendPort and ReceivePort for message passing and the custom logic for receiving the arguments and sending the progress back to the main Isolate.<\/p>\n<h2 id=\"20e0\" class=\"afv afw yr bu yb qn afx qo qr qs afy qt qw abe afz aga rb abi agb agc rg abm agd age rl agf bx\" data-selectable-paragraph=\"\">What are Isolate Groups?<\/h2>\n<p id=\"df01\" class=\"pw-post-body-paragraph zw zx yr rn b zy agg ud aba abb agh ug abd abe agi abg abh abi agj abk abl abm agk abo abp abq ob bx\" data-selectable-paragraph=\"\">So, we already know how Isolates passes messages to each other. But let\u2019s assume, the message we are passing is a huge JSON. Before Dart 2.15, this huge object passing, could involve stutter in UI. This is because, we already know that Isolate has some memory, and when one Isolate passes an object to the other, that object had to be deep copied. This meant, a lot of time for copying the object to the main Isolate which can cause a jank.<\/p>\n<p id=\"c5ad\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">To avoid this circumstance, Isolates were reworked and Isolate Groups were invented. Isolate Groups, meaning a group of isolates, which share some common internal data structures representing the running application. This means each time a new Isolate is spawned, new internal data structures don\u2019t need to be constructed again. Because they share them together.<\/p>\n<p id=\"d89e\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">Don\u2019t confuse these internal data structures with the mutable objects. The Isolates still can\u2019t share this memory with each other. Message passing is still needed. But, because Isolates in the same Isolate group, share the same heap, this means spawning a new Isolate is 100 times faster and consume 10\u2013100 times less memory.<\/p>\n<p id=\"69f1\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">An example is a worker isolate that makes a network call to get data, parses that data into a large JSON object graph, and then returns that JSON graph to the main isolate. Before Dart 2.15, that result needed to be deep-copied, which could itself cause UI jank if the copy took longer than the frame budget. This means that the main Isolate can receive this JSON in almost constant time. And sending messages is now approximately 8 times faster.<\/p>\n<p id=\"f299\" class=\"pw-post-body-paragraph zw zx yr rn b zy zz ud aba abb abc ug abd abe abf abg abh abi abj abk abl abm abn abo abp abq ob bx\" data-selectable-paragraph=\"\">The good news is that, if you\u2019re using Flutter version greater than 2.8, you don\u2019t need to do anything to use these advancements.<\/p>\n<blockquote>\n<p data-selectable-paragraph=\"\">Hope you liked the understanding of Isolates. If you have any doubts, please comment.<\/p>\n<\/blockquote>\n<p data-selectable-paragraph=\"\">Reference for code: <a href=\"https:\/\/github.com\/DhruvamSharma\/NFT-Material3\">https:\/\/github.com\/DhruvamSharma\/NFT-Material3<\/a><\/p>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>I have always wondered what set of code to run in the background to make my app powerful and responsive but I don\u2019t really know how. Some time back I got to know about isolates and I tried implementing it. And I should tell you, it was painful. But I recently discovered how easy it [&hellip;]<\/p>\n","protected":false},"author":1554,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":6},"categories":[4687],"tags":[4845,4968,398,4848],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/56777"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1554"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=56777"}],"version-history":[{"count":2,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/56777\/revisions"}],"predecessor-version":[{"id":56797,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/56777\/revisions\/56797"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=56777"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=56777"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=56777"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}