selectionStream method

BehaviorSubject<TextSelection> selectionStream()

A BehaviorSubject that will update selection when a new event is emitted, also emits a new event when selection changes

Implementation

BehaviorSubject<TextSelection> selectionStream() {
  final stream = BehaviorSubject<TextSelection>.seeded(this.selection);
  bool isLock = false;

  // Set a new text to controller
  // when stream is emitted
  stream.listen((data) {
    if (isLock) return;
    isLock = true;
    this.selection = data;
    isLock = false;
  });

  // Set value back to stream
  // when the text got changed in controller
  this.addListener(() async {
    if (isLock) return;
    isLock = true;
    stream.value = this.selection;
    await Future.delayed(Duration(microseconds: 1));
    isLock = false;
  });
  return stream;
}