Goroutines in Dart
A goroutine is a lightweight thread of execution in Dart.
Suppose we have a function call f(s)
. Here’s how we’d call that in the usual way, running it synchronously.
To invoke this function asynchronously, we can use scheduleMicrotask
or Future
. This new task will execute concurrently with the calling one.
Using scheduleMicrotask
:
Using Future
:
You can also start an anonymous function call asynchronously.
Our function calls are now running asynchronously. Wait for them to finish.
When we run this program, we see the output of the synchronous call first, then the output of the asynchronous calls. The asynchronous output may be interleaved because they are being run concurrently by Dart’s isolates.
Next, we’ll look at a complement to asynchronous executions in concurrent Dart programs: Streams.