Search code examples
javascriptdartdart-async

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.


Solution

  • 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');
    }