0

I'm trying to understand how to use streams to notify listeners when there is a new addition to a list, below I wrote an example program that sums up what I'm trying to accomplish. Everytime there is a NEW string added to the existing 'names' list, I would like the stream to notify its listeners.

import 'dart:async';
import 'dart:io';
import 'dart:math';

List<String> names = ['matt', 'luke', 'sam'];

// pushes random string onto 'names' list every 3 seconds
void addNamesToNameList() async {
  Random random = Random();
  int len = 4;
  while(true) {
    String new_name = String.fromCharCodes(List.generate(len, (index) => random.nextInt(33) + 89));
    names.add(new_name);
    print("Added $new_name to names list");
    sleep(Duration(seconds: 3));
  }
}

void main() {
  addNamesToNameList();

  /*
    Insert stream that is notified every time there is a NEW addition to the 'names' list
  */
}
OBurnsy22
  • 29
  • 3

1 Answers1

0

You can use Stream.periodic to accomplish this.

  
  late final List<String> names = [];

  late final Stream<String> stream = randomStream().asBroadcastStream();
  
  //use [asBroadcastStream] if you have multiple listeners.

  String generateNewName(int i) {
    Random random = Random();
    int len = 4;
    return String.fromCharCodes(
        List.generate(len, (index) => random.nextInt(33) + 89));
  }

  Stream<String> randomStream() async* {
    yield* Stream.periodic(
      const Duration(seconds: 3),
      generateNewName,
    ).asyncMap((event) => event);
  }

and then listen to changes:

   stream.listen((event) {
      setState(() => names.add(event));
    });
Soliev
  • 1,180
  • 1
  • 1
  • 12