Skip to content

Instantly share code, notes, and snippets.

@pyetti
Created August 6, 2019 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyetti/c97d906a9c6f744a4ba20425c594cc32 to your computer and use it in GitHub Desktop.
Save pyetti/c97d906a9c6f744a4ba20425c594cc32 to your computer and use it in GitHub Desktop.
Stream transforms in Dart are too complicated and seem to require the below over and over, if it's not generic. The file below should be useable in any Dart project to transform streams.
import 'dart:async';
/*
* https://api.flutter.dev/flutter/dart-async/Stream/Stream.eventTransformed.html
*
* <S, T>
* S ==> Snapshot type (DocumentSnapshot, QuerySnapshot, et. al.)
* T ==> The type to be returned (Event, List<EventMedia>, et. al.)
*
* This should probably never need to change. It seems to work pretty well.
*
* Pass instance of EventStreamTransformer<S, T> to stream.transform. Pass in a callback
* function that will do the actual transformation. T will be the returned stream type
*
* Example:
* return stream.transform(EventStreamTransformer<DocumentSnapshot, Event>(
* (DocumentSnapshot documentSnapshot) {
* Event event = EventSerializer.documentSnapshotFromFirestore(documentSnapshot);
* event.id = documentSnapshot.documentID;
* return event;
* }));
* */
class EventStreamTransformer<S, T> extends StreamTransformerBase<S, T> {
final Function _transform;
EventStreamTransformer(this._transform);
@override
Stream<T> bind(Stream<S> stream) {
return Stream<T>.eventTransformed(
stream,
(EventSink sink) => EventStreamSink<S, T>(sink, _transform),
);
}
}
class EventStreamSink<S, T> implements EventSink<S> {
final EventSink<T> _outputSink;
final Function _transform;
EventStreamSink(this._outputSink, this._transform);
@override
void add(S snapshot) {
T transformed = _transform(snapshot);
_outputSink.add(transformed);
}
@override
void addError(Object error, [StackTrace stackTrace]) {
_outputSink.addError(error, stackTrace);
}
@override
void close() {
_outputSink.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment