RxDart
About
RxDart adds additional capabilities to Dart Streams and StreamControllers.
Dart comes with a very decent Streams API out-of-the-box; rather than attempting to provide an alternative to this API, RxDart adds functionality from the reactive extensions specification on top of it.
RxDart does not provide its own Observable class as a replacement for Dart Streams. Rather, it provides a number of additional Stream classes, operators (extension methods on the Stream class), and Subjects.
If you are familiar with Observables from other languages, please see the Rx Observables vs Dart Streams comparison chart for notable distinctions between the two.
Upgrading from RxDart 0.22.x to 0.23.x
RxDart 0.23.x moves away from the Observable class, utilizing Dart 2.6’s new extension methods instead. This requires several small refactors that can be easily automated — which is just what we’ve done!
Please follow the instructions on the rxdart_codemod package to automatically upgrade your code to support RxDart 0.23.x.
How To Use RxDart
For Example: Reading the Konami Code
import 'package:rxdart/rxdart.dart'; void main() { const konamiKeyCodes = const <int>[ KeyCode.UP, KeyCode.UP, KeyCode.DOWN, KeyCode.DOWN, KeyCode.LEFT, KeyCode.RIGHT, KeyCode.LEFT, KeyCode.RIGHT, KeyCode.B, KeyCode.A, ]; final result = querySelector('#result'); document.onKeyUp .map((event) => event.keyCode) .bufferCount(10, 1) // An extension method provided by rxdart .where((lastTenKeyCodes) => const IterableEquality<int>().equals(lastTenKeyCodes, konamiKeyCodes)) .listen((_) => result.innerHtml = 'KONAMI!'); }
API Overview
RxDart adds functionality to Dart Streams in three ways:
- Stream Classes – create Streams with specific capabilities, such as combining or merging many Streams together.
- Extension Methods – transform a source Stream into a new Stream with different capabilities, such as throttling or buffering events.
- Subjects – StreamControllers with additional powers
Stream Classes
The Stream class provides different ways to create a Stream: Stream.fromIterable
or Stream.periodic
, for example. RxDart provides additional Stream classes for a variety of tasks, such as combining or merging Streams together!
You can construct the Streams provided by RxDart in two ways. The following examples are equivalent in terms of functionality:
- Instantiating the Stream class directly.
- Example:
final mergedStream = MergeStream([myFirstStream, mySecondStream]);
- Example:
- Using static factories from the
Rx
class, which are useful for discovering which types of Streams are provided by RxDart. Under the hood, these factories simply call the the corresponding Stream constructor.- Example:
final mergedStream = Rx.merge([myFirstStream, mySecondStream]);
- Example:
List of Classes / Static Factories
- ConcatStream / Rx.concat
- ConcatEagerStream / Rx.concatEager
- DeferStream / Rx.defer
- MergeStream / Rx.merge
- NeverStream / Rx.never
- RaceStream / Rx.race
- RepeatStream / Rx.repeat
- RetryStream / Rx.retry
- RetryWhenStream / Rx.retryWhen
- SequenceEqualStream / Rx.sequenceEqual
- SwitchLatestStream / Rx.switchLatest
- TimerStream / Rx.timer
- CombineLatestStream (combine2, combine3… combine9) / Rx.combineLatest2…Rx.combineLatest9
- ForkJoinStream (join2, join3… join9) / Rx.forkJoin2…Rx.forkJoin9
- RangeStream / Rx.range
- ZipStream (zip2, zip3, zip4, …, zip9) / Rx.zip…Rx.zip9
Extension Methods
The extension methods provided by RxDart can be used on any Stream
. They convert a source Stream into a new Stream with additional capabilities, such as buffering or throttling events.
Example
Stream.fromIterable([1, 2, 3]) .throttleTime(Duration(seconds: 1)) .listen(print); // prints 3
List of Extension Methods
- buffer
- bufferCount
- bufferTest
- bufferTime
- concatWith
- debounce
- debounceTime
- defaultIfEmpty
- delay
- dematerialize
- distinctUnique
- doOnCancel
- doOnData
- doOnDone
- doOnEach
- doOnError
- doOnListen
- doOnPause
- doOnResume
- exhaustMap
- flatMap
- flatMapIterable
- groupBy
- interval
- mapTo
- materialize
- max
- mergeWith
- min
- onErrorResume
- onErrorResumeNext
- onErrorReturn
- onErrorReturnWith
- pairwise
- sample
- sampleTime
- scan
- skipUntil
- startWith
- startWithMany
- switchIfEmpty
- switchMap
- takeUntil
- throttle
- throttleTime
- timeInterval
- timestamp
- whereType
- window
- windowCount
- windowTest
- windowTime
- withLatestFrom
- zipWith
Subjects
Dart provides the StreamController class to create and manage a Stream. RxDart offers two additional StreamControllers with additional capabilities, known as Subjects:
- BehaviorSubject – A broadcast StreamController that caches the latest added value or error. When a new listener subscribes to the Stream, the latest value or error will be emitted to the listener. Furthermore, you can synchronously read the last emitted value.
- ReplaySubject – A broadcast StreamController that caches the added values. When a new listener subscribes to the Stream, the cached values will be emitted to the listener.
Rx Observables vs Dart Streams
In many situations, Streams and Observables work the same way. However, if you’re used to standard Rx Observables, some features of the Stream api may surprise you. We’ve included a table below to help folks understand the differences.
Additional information about the following situations can be found by reading the Rx class documentation.
Situation | Rx Observables | Dart Streams |
---|---|---|
An error is raised | Observable Terminates with Error | Error is emitted and Stream continues |
Cold Observables | Multiple subscribers can listen to the same cold Observable, each subscription will receive a unique Stream of data | Single subscriber only |
Hot Observables | Yes | Yes, known as Broadcast Streams |
Is {Publish, Behavior, Replay}Subject hot? | Yes | Yes |
Single/Maybe/Complete ? | Yes | No, uses Dart Future |
Support back pressure | Yes | Yes |
Can emit null? | Yes, except RxJava | Yes |
Sync by default | Yes | No |
Can pause/resume a subscription*? | No | Yes |
Examples
Web and command-line examples can be found in the example
folder.
Web Examples
In order to run the web examples, please follow these steps:
- Clone this repo and enter the directory
- Run
pub get
- Run
pub run build_runner serve example
- Navigate to http://localhost:8080/web/ in your browser
Command Line Examples
In order to run the command line example, please follow these steps:
- Clone this repo and enter the directory
- Run
pub get
- Run
dart example/example.dart 10
Flutter Example
Install Flutter
In order to run the flutter example, you must have Flutter installed. For installation instructions, view the online documentation.
Run the app
- Open up an Android Emulator, the iOS Simulator, or connect an appropriate mobile device for debugging.
- Open up a terminal
cd
into theexample/flutter/github_search
directory- Run
flutter doctor
to ensure you have all Flutter dependencies working. - Run
flutter packages get
- Run
flutter run
Notable References
Changelog
Refer to the Changelog to get all release notes.
Download RxDart – The Reactive Extensions for Dart Source Code on GitHub
Provides the list of the opensource Flutter apps collection with GitHub repository.