Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript callback to Dart future

I'm trying to convert the following snippet from Node.js to Dart.

 self.emit('send_message_A', foo, bar, function(opt1, opt2) {
   var avar= self.getSomeValue(foo, bar, opt1, opt2);

   if(self.someCondition)
     self.emit('send_message_B', foo, bar, avar);
 });

Any help is greatly appreciated. Thanks in advance.

Edit: So far I've tried:

typedef Future Next(String opt1, String opt2);

class Sender {
  Stream<Next> get onSendMessageA => sendMessageA.stream;
  final sendMessageA = new StreamController<Next>.broadcast();

  SendMessage(fn) => sendMessageA.add(fn);
}

main() {
  var sender = new Sender()
    ..onSendMessageA.listen((f) => f('option1', 'option2'))
      .asFuture().then((value) => print('value: $value'));

  Future<String> fn(String opt1, String opt2) {
    print('opt1: $opt1');
    print('opt2: $opt2');
    return new Future.value('$opt1 - $opt2');
  };

  sender.sendMessageA(fn);
}

Option 1 and 2 gets printed but no future value is returned.

like image 561
basheps Avatar asked Sep 04 '26 06:09

basheps


2 Answers

You call sendMessageA but that is only a field that references the StreamController, what you want is to call SendMessage(). You should make sendMessageA private (_sendMessage) and start SendMessage with a lowercase letter (Dart style guid) and then call sendMessage() that adds fn to _sendMessage.

Tried the following code and worked.

library x;

import 'dart:async';

typedef Future<String> Next(String opt1, String opt2);

class Sender {
  Stream<Next> get onSendMessageA => _sendMessageA.stream;
  final _sendMessageA = new StreamController<Next>.broadcast();

  sendMessage(fn) => _sendMessageA.add(fn);
}

void main(List<String> args) {
  var sender = new Sender()
    ..onSendMessageA.listen((f) {
      f('option1', 'option2')
      .then((value) => print('value: $value'));
    });


  sender.sendMessage(fn);
}

Future<String> fn(String opt1, String opt2) {
  print('opt1: $opt1');
  print('opt2: $opt2');
  return new Future.value('$opt1 - $opt2');
}
like image 91
Günter Zöchbauer Avatar answered Sep 05 '26 19:09

Günter Zöchbauer


We can also use Completers as its very easy to use See the Doc API for how to use and concrete examples

like image 27
youssef Avatar answered Sep 05 '26 18:09

youssef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!