Yonkee
Yonkee

Reputation: 1883

Race condition with stream listen

I have an async function like below. However content is being returned null well before the stream listening is done.

I started playing out with Future.delayed, but thought better of it and wanted to ask if there is a better approach to ensure this is async?

import 'package:googleapis/drive/v3.dart' as ga;

static Future<String> getContentsFromFile() async {
String content;

ga.Media mediaResponse = await drive.files.get(fileId);

mediaResponse.stream.listen((data) {
    print("DataReceived: "+data);
    content = data
  }, onDone: () async {
    print("Task Done");
  }, onError: (error) {
    print("Some Error");
  });
return content;
}

Im calling the function like so..

String content = await getContentsFromFile();

Upvotes: 2

Views: 583

Answers (1)

matehat
matehat

Reputation: 5374

EDIT: Made the example more complete, with handling of errors and partial content.

You can use Completer for this sort of control flow:

import 'dart:async';
import 'package:googleapis/drive/v3.dart' as ga;

static Future<String> getContentsFromFile() async {
  Completer<String> completer = Completer();
  String content = "";

  ga.Media mediaResponse = await drive.files.get(fileId);

  mediaResponse.stream.listen((data) {
    print("DataReceived: "+data);
    content += data;
  }, onDone: () async {
    print("Task Done");
    completer.complete(content);
  }, onError: (error) {
    print("Some Error");
    completer.completeError(error);
  });

  return completer.future;
}

Upvotes: 3

Related Questions