Junior — Middle
Can you explain what coroutines are and how they work in programming?
sobes.tech AI
Answer from AI
Coroutines are special functions that can suspend their execution and later resume it, allowing efficient handling of asynchronous operations without blocking the main thread.
In Flutter (Dart), coroutines are implemented through async/await and Future. When a function is marked as async, it returns a Future and can use await to wait for the result of an asynchronous operation without blocking.
Example:
Future<void> fetchData() async {
print('Starting download');
await Future.delayed(Duration(seconds: 2)); // simulate delay
print('Data loaded');
}
void main() {
fetchData();
print('Function called');
}
The output will be:
Starting download
Function called
Data loaded
This shows that execution is not blocked during waiting, and the coroutine is suspended and resumed later.