What is the difference between Future and Stream in Dart

What is the difference between Future and Stream in Dart

Introduction:

Today I'll talk about what are the differences between Future and Stream in Dart but before that, let me give you a brief introduction to what's Asynchronous programming in the first place:

Asynchronous Programming:

Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the main application thread. When the work is complete, it notifies the main thread, allowing the application to remain responsive.

Why Use Asynchronous Programming?

  • Non-blocking Operations: Asynchronous programming is essential for tasks that might take a significant amount of time, such as network requests, file I/O or database operations. By performing these tasks asynchronously, you ensure that the main application thread remains responsive, providing a better user experience.
  • Concurrency: It allows for performing multiple operations concurrently, which can improve the performance and responsiveness of applications.

Asynchronous programming in Dart:

Asynchronous programming in Dart allows you to perform tasks that might take some time, such as network requests or file I/O, without blocking the main thread. Dart provides several tools to work with asynchronous operations, primarily using Future and Stream.

Key Concepts:

  1. Future: Represents a single asynchronous computation that produces a value or an error.
  2. Stream: Represents a sequence of asynchronous events or values over time.

Future

A Future represents a single asynchronous computation that will eventually complete with a value or an error. It is used for operations that will produce a single result at some point in the future.

Characteristics of Future:

  • Single Value: A Future provides a single value (or an error) when the asynchronous operation completes.
  • Single Subscription: A Future can have only one listener that gets notified when the computation is complete.
  • Simpler Use Case: Futures are ideal for straightforward, one-time operations like fetching data from a network, reading a file, or performing a computation that will produce a result once.

Example of Future:

Future<String> fetchData() async {
  // Simulate a network request
  await Future.delayed(Duration(seconds: 2));
  return 'Data fetched';
}

void main() {
  fetchData().then((data) {
    print(data);  // Output: Data fetched
  }).catchError((error) {
    print('Error: $error');
  });
}        

Stream

A Stream represents a sequence of asynchronous events over time. It is used for operations that produce multiple values over a period.

Characteristics of Stream:

  • Multiple Values: A Stream can provide multiple values (or errors) over time.
  • Multiple Listeners: Depending on the type of stream, it can support multiple listeners. Broadcast streams can have multiple listeners, while single-subscription streams can have only one listener at a time.
  • Complex Use Case: Streams are suitable for continuous data flows or event-driven scenarios like user inputs, real-time updates, or any situation where you need to handle multiple asynchronous events.

Example of Stream:

import 'dart:async';

Stream<int> countStream(int max) async* {
  for (int i = 1; i <= max; i++) {
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

void main() {
  final stream = countStream(5);
  stream.listen((count) {
    print(count);  // Output: 1 2 3 4 5 (one per second)
  }, onError: (error) {
    print('Error: $error');
  }, onDone: () {
    print('Done');
  });
}
        

Key Differences

Nature of Asynchronous Operations:

  • Future: Handles a single asynchronous operation.
  • Stream: Handles a series of asynchronous operations/events over time.

Number of Values:

  • Future: Completes with a single value or an error.
  • Stream: Can emit multiple values or errors over time.

Listeners:

  • Future: Can have only one listener.
  • Stream: Can have multiple listeners in case of broadcast streams, but single-subscription streams can have only one listener.

Use Cases:

  • Future: Ideal for operations like fetching data, reading files, or any one-time task
  • Stream: Ideal for handling continuous data like UI events, real-time data feeds, or any scenario involving multiple asynchronous events.

Summary

  • Future: Use Future for a single asynchronous result.
  • Stream: Use Stream for multiple asynchronous results over time.

Understanding the difference between Future and Stream helps you choose the right tool for the right scenario, making your asynchronous code in Dart more effective and easier to manage.

Aayush Paigwar

Flutter Developer @ProCohat | Azure | LLM | Beta Microsoft Student Ambassador | Artificial Intelligence Student

6 个月

Great explanation of Future vs Stream in Dart! Perfect for understanding async programming! ?? #Dart #Async #Flutter

回复

要查看或添加评论,请登录

Omer Elkhalifa的更多文章

  • ?? Embracing Command Query Separation in Your Codebase ??

    ?? Embracing Command Query Separation in Your Codebase ??

    Command Query Separation (CQS) is a powerful principle in software design that advocates for a clear distinction…

  • Object Relational Mapping

    Object Relational Mapping

    ?????? ?? ????? ?? ????? ???? ? ???? ? ???? ????? ????? ???? ???? ?? ??? ????? ???????? ??? ? ?? ?? ORM ??? ??? ??…

  • Test-Driven Development

    Test-Driven Development

    ? ??? ??????? ?? ?? Testing? ? ????? ?? ?? ????? ?? Test-Driven Development ?? ??????? ???????? ?????????. ??? ??…

  • Types of Automated Test

    Types of Automated Test

    ?? ????? ?????? ??????? ?? ?? ????? ?? ?? Testing ? ??????? ??????? ???????? ?????? ?? ???? ??? ?? ????? ?? Automated…

  • Testing

    Testing

    ?????? ?? ????? ?? ?? Testing? ??? ? ?? ???? ??? ??????? ?? ??? ???? ?? ?????? . ?? ????? ????????? ? ????? ???? ??????…

  • ????? ?? APIs

    ????? ?? APIs

    ?? ????? ??????? ?????? ?? ??SDK ? ????? ???? ????? ????? ????? ?? ????? ?? APIs , ? ?? ????? ?????? ?? ??? ????. ???…

  • ??? ????? ???? ?????? ?????????

    ??? ????? ???? ?????? ?????????

    ??? ??? ???? ?? ????? ??SDK ? ??? ???? ??????? ??? ?? ???? ?? ????? ?? ??? ? ?? SDK ?????? ?? Software Development Kit…

  • DRY Principle

    DRY Principle

    "?Repetition is the root for all software evil". ?? Dry ?????? ?? Don't Repeat Yourself ? ?? ????? ?? ????? ?? ?????…

社区洞察

其他会员也浏览了