How to create a Dart Stream from a JavaScript listener

256 Views Asked by At

I would like to create a Stream which should contain the same elements like the callback in the following code:

chromeTabs['onUpdated'].callMethod('addListener', 
    [(tabId, changeInfo, tab) => print("tabId = $tabId")]);

I read the tutorials/articles from Chris Buckett and am not sure if it is possible to create a Stream elements at the moments when the first Consumer comes. In the code above, it would mean to get the javascript listener registered when the Dart Stream get listened.

The following code cannot work due to referencing to updateStreamController before it is being initialised:

var updateStreamController = new StreamController<int>(onListen: () =>
    chromeTabs['onUpdated'].callMethod('addListener', [(tabId, changeInfo, tab) => 
        updateStreamController.add(tabId)]);`

Unfortunately, the onListen property is only settable via the constructor.

Thanks in advance for your help

1

There are 1 best solutions below

0
On BEST ANSWER

You can simply declare the variable before to initialize it :

var updateStreamController;
updateStreamController = new StreamController<int>(onListen: () => 
    chromeTabs['onUpdated'].callMethod('addListener', 
        [(tabId, changeInfo, tab) => updateStreamController.add(tabId)]));