Home > OS >  Create a stream watching a list?
Create a stream watching a list?

Time:10-30

I've got a global list like this:

var data = [1,2,3];

I will add more elements to it, and each time I do I want something else to be notified - I need a stream and listener. So can I make a stream and tell it to run sink.add anytime the list mutates?

var stream = Stream.fromIterable(data);
stream.listen((item) => print(item));
> 1
> 2
> 3

data.add(4);
> Uncaught Error: Concurrent modification during iteration
data.remove(3);
> Uncaught Error: Concurrent modification during iteration

Oh no. What can I do to make this work?

CodePudding user response:

This might help:

import 'dart:async';

class  ObservableList<T> {
  final _list = <T>[];
  
  final _itemAddedStreamController = StreamController<T>();
  
  final _listStreamController = StreamController<List<T>>();
  
  Stream get itemAddedStream => _itemAddedStreamController.stream;
  
  Stream get listStream => _listStreamController.stream;
  
  
  void add(T value) {
    _list.add(value);
    _itemAddedStreamController.add(value);
    _listStreamController.add(_list);
  }
  
  void dispose() {
    _listStreamController.close();
    _itemAddedStreamController.close();
  }
}

void main() {
  final observableList = ObservableList<int>();
  
  observableList.itemAddedStream.listen((value) => print(value));
  
  observableList.add(1);
  observableList.add(2);
  observableList.add(3);
  observableList.add(4);
}
  • Related