dart - async Future StreamSubscription Error -
could please explain what's wrong following code. i'm making 2 calls function finputdata. first works ok, second results in error : "unhandled exception" "bad state: stream has subscriber"
i need write test console program inputs multiple parameters.
import "dart:async" async; import "dart:io"; void main() { finputdata ("enter nr of iterations : ") .then((string sresult){ int iiters; try { iiters = int.parse(sresult); if (iiters < 0) throw new exception("invalid"); } catch (oerror) { print ("invalid entry"); exit(1); } print ("in main : iterations selected = ${iiters}"); finputdata("continue processing? (y/n) : ") // call bombs .then((string sinput){ if (sinput != "y" && sinput != "y") exit(1); fprocessdata(iiters); print ("main completed"); }); }); } async.future<string> finputdata(string sprompt) { async.completer<string> ocompleter = new async.completer(); stdout.write(sprompt); async.stream<string> ostream = stdin.transform(new stringdecoder()); async.streamsubscription osub; osub = ostream.listen((string sinput) { ocompleter.complete(sinput); osub.cancel(); }); return ocompleter.future; } void fprocessdata(int iiters) { print ("in fprocessdata"); print ("iiters = ${iiters}"); (int ipos = 1; ipos <= iiters; ipos++ ) { if (ipos%100 == 0) print ("processed = ${ipos}"); } print ("in fprocessdata - completed ${iiters}"); }
some background reading:
streams comes in 2 flavours: single or multiple (also known broadcast) subscriber. default, our stream single-subscriber stream. means if try listen stream more once, exception, , using of callback functions or future properties counts listening.
you can convert single-subscriber stream broadcast stream using asbroadcaststream() method.
so you've got 2 options - either re-use single subscription object. i.e. call listen once, , keep subscription object alive.
or use broadcast stream - note there number of differences between broadcast streams , single-subscriber streams, you'll need read , make sure suit use-case.
here's example of reusing subscriber ask multiple questions:
import 'dart:async'; import 'dart:io'; main() { var console = new console(); var loop; loop = () => ask(console).then((_) => loop()); loop(); } future ask(console console) { print('1 + 1 = ...'); return console.readline().then((line) { print(line.trim() == '2' ? 'yup!' : 'nope :('); }); } class console { streamsubscription<string> _subs; console() { var input = stdin .transform(new stringdecoder()) .transform(new linetransformer()); _subs = input.listen(null); } future<string> readline() { var completer = new completer<string>(); _subs.ondata(completer.complete); return completer.future; } }
Comments
Post a Comment