Created
April 14, 2020 21:39
-
-
Save rrousselGit/cd0f5a0dd5f77f2df58343ed999b0fe4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension AsValueListenable<T> on Stream<T> { | |
/// Converts a [Stream] to a [ValueListenable] | |
/// | |
/// The internal [StreamSubscription] is cancelled when | |
/// all listeners added to [ValueListenable] are removed. | |
/// Keep this in mind as this could cause issues with | |
/// single-subscription streams. | |
ValueListenable<T> asValueListenable(T initialValue) { | |
return _StreamValueListenable(this, initialValue); | |
} | |
} | |
class _StreamValueListenable<T> extends ValueNotifier<T> { | |
_StreamValueListenable(this.stream, T initialValue) : super(initialValue); | |
final Stream<T> stream; | |
StreamSubscription<T> subscription; | |
@override | |
void addListener(VoidCallback listener) { | |
subscription ??= stream.listen((event) { | |
value = event; | |
}); | |
super.addListener(listener); | |
} | |
@override | |
void removeListener(VoidCallback listener) { | |
super.removeListener(listener); | |
if (!hasListeners && subscription != null) { | |
subscription.cancel(); | |
subscription = null; | |
} | |
} | |
} |
You may want to override the RemoveListener function to unsubscribe too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would the ValueNotifier version look something like the following?