5- Mastering Asynchronous Programming in Dart for Java Developers

image 2

Play Store Application link – Java to Dart in 10 Steps – App on Google Play

Asynchronous programming is crucial for writing efficient, non-blocking code, especially when dealing with I/O operations, such as fetching data from a server or reading files. If you’re familiar with Java, Dart’s approach to asynchronous programming will have some familiar concepts but also some unique features. In this blog post, we’ll cover Dart’s Future and Stream for handling asynchronous tasks, comparing them with Java’s Future and Stream (via CompletableFuture and Stream API) to help you get up to speed.

1. Future and Async/Await

Understanding Future and FutureBuilder

In Dart, a Future represents a value that will be available at some point in the future. It’s similar to Java’s CompletableFuture. You use it to perform asynchronous operations like fetching data from an API or reading a file.

  • Java: import java.util.concurrent.CompletableFuture; CompletableFuture.supplyAsync(() -> {
    // Simulate a long-running task return "Hello, World!"; }).thenAccept(result -> { System.out.println(result); });
  • Dart: import 'dart:async';
    Future<void> main() async {
    var result = await fetchGreeting();
    print(result);
    }
    Future<String> fetchGreeting() async {
    return Future.delayed(Duration(seconds: 2), () => 'Hello, World!');
    }

In Dart, Future is used with async and await keywords to simplify handling asynchronous operations. The await keyword pauses the function until the Future completes, much like how thenAccept is used with CompletableFuture in Java.

Async and Await Keywords

  • Java: import java.util.concurrent.CompletableFuture;
    public class Main {
    public static void main(String[] args) { CompletableFuture.supplyAsync(() -> {
    // Simulate a long-running task return "Hello, World!"; }).thenAccept(result -> { System.out.println(result); });
    }
    }
  • Dart: import 'dart:async';
    Future<void> main() async {
    var result = await fetchGreeting();
    print(result);
    }
    Future<String> fetchGreeting() async {
    return Future.delayed(Duration(seconds: 2), () => 'Hello, World!');
    }

In Dart, async is used to mark a function that returns a Future, and await is used inside such functions to pause execution until the Future completes. This is conceptually similar to how Java’s CompletableFuture works with asynchronous tasks.

2. Streams

Creating and Using Streams

Streams in Dart are used for handling multiple asynchronous events, similar to Java’s Stream API. They are useful for continuous data flows, like receiving real-time updates from a server.

  • Java: import java.util.concurrent.Flow;
    import java.util.concurrent.SubmissionPublisher;
    public class Main { public static void main(String[] args) { SubmissionPublisher<String> publisher = new SubmissionPublisher<>(); publisher.subscribe(new Flow.Subscriber<String>() {
    @Override
    public void onSubscribe(Flow.Subscription subscription) { subscription.request(Long.MAX_VALUE);
    }
    @Override public void onNext(String item) {
    System.out.println(item);
    }
    @Override
    public void onError(Throwable throwable) {
    throwable.printStackTrace();
    }
    @Override
    public void onComplete() {
    System.out.println("Completed!");
    }
    });
    publisher.submit("Hello, World!");
    publisher.close();
    }
    }
  • Dart: import 'dart:async';
    void main() {
    var streamController = StreamController<String>(); streamController.stream.listen((data) {
    print(data);
    }, onDone: () {
    print('Stream closed!');
    });
    streamController.add('Hello, World!');
    streamController.close();
    }

In Dart, StreamController is used to create a stream, and you can listen to it using the listen method. This is analogous to Java’s SubmissionPublisher and Flow.Subscriber.

Stream Methods (listen, transform, etc.)

Streams offer several methods to handle data:

  • Java: import java.util.Arrays;
    import java.util.List;
    public class Main {
    public static void main(String[] args) {
    List<String> items = Arrays.asList("One", "Two", "Three"); items.stream() .filter(item -> item.startsWith("T")) .forEach(System.out::println);
    }
    }
  • Dart: import 'dart:async';
    void main() {
    var stream = Stream.fromIterable(['One', 'Two', 'Three']); stream.where((item) => item.startsWith('T')) .listen((item) => print(item));
    }

Dart streams support various operations such as where, map, and transform, similar to Java’s Stream API. In Dart, where filters the stream items, similar to Java’s filter.

Leave a Reply

Your email address will not be published. Required fields are marked *