Alexey Adamovskiy Alexey Adamovskiy - 3 months ago 9
Dart Question

Force stream events delivery

I am trying to test stream events in my service, and faced a problem: is any way to synchronously deliver events in async stream? Here is simplified code example:

test("deliver event", () {
StreamController sc = new StreamController();
String v = "old";
sc.stream.listen((val) {v = val;});
sc.add("new");
expect(v, "new"); // test fails: actual value is "old"
});

Answer

You can't make anything from async to sync.

import 'dart:async';
Future main() async {
  StreamController sc = new StreamController();
  String v = "old";
  var subscr = sc.stream.listen((val) { v = val;});
  sc.add("new");
  subscr.asFuture().then((_) {
    print('assert v == "new": ${v == 'new'}'); 
    // expect(v, "new"); // test fails: actual value is "old"
  });
  sc.close();
}

DartPad example