{"id":20609505,"url":"https://github.com/fluttercommunity/rx_command","last_synced_at":"2025-04-09T12:08:44.623Z","repository":{"id":50986624,"uuid":"128074634","full_name":"fluttercommunity/rx_command","owner":"fluttercommunity","description":"RxCommand - Reactive event handler wrapper class inspired by ReactiveUI. Maintainer @escamoteur","archived":false,"fork":false,"pushed_at":"2024-08-08T04:56:41.000Z","size":1326,"stargazers_count":135,"open_issues_count":2,"forks_count":23,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-02T03:59:50.326Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/rx_command","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fluttercommunity.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["escamoteur"],"custom":["https://www.buymeacoffee.com/escamoteur"]}},"created_at":"2018-04-04T14:31:44.000Z","updated_at":"2024-11-17T18:49:59.000Z","dependencies_parsed_at":"2024-12-18T17:10:42.354Z","dependency_job_id":"0af324ff-09e1-4c83-9033-c9541c2434de","html_url":"https://github.com/fluttercommunity/rx_command","commit_stats":{"total_commits":132,"total_committers":10,"mean_commits":13.2,"dds":"0.12878787878787878","last_synced_commit":"ea5bfe40cc5095c0dd07d5dd1f115d7ee52c5201"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluttercommunity%2Frx_command","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluttercommunity%2Frx_command/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluttercommunity%2Frx_command/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluttercommunity%2Frx_command/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fluttercommunity","download_url":"https://codeload.github.com/fluttercommunity/rx_command/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248036067,"owners_count":21037092,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-16T10:13:45.161Z","updated_at":"2025-04-09T12:08:44.591Z","avatar_url":"https://github.com/fluttercommunity.png","language":"Dart","funding_links":["https://github.com/sponsors/escamoteur","https://www.buymeacoffee.com/escamoteur"],"categories":[],"sub_categories":[],"readme":"[![Flutter Community: rx_command](https://fluttercommunity.dev/_github/header/rx_command)](https://github.com/fluttercommunity/community)\r\n\r\n# RxCommand\r\n\r\n\u003e **BREAKING CHANGE with V5.0** RxCommand no longer works with Observables but with plain Dart Streams because the latest RxDart version now uses extension methods on Streams instead of Observables:\r\n\u003e\r\n```Dart\r\nstatic RxCommand\u003cTParam, TResult\u003e createSync\u003cTParam, TResult\u003e(Func1\u003cTParam, TResult\u003e func,...\r\nstatic RxCommand\u003cvoid, TResult\u003e createSyncNoParam\u003cTResult\u003e(Func\u003cTResult\u003e func,...\r\nstatic RxCommand\u003cTParam, void\u003e createSyncNoResult\u003cTParam\u003e(Action1\u003cTParam\u003e action,...\r\nstatic RxCommand\u003cvoid, void\u003e createSyncNoParamNoResult(Action action,...\r\n\r\nstatic RxCommand\u003cTParam, TResult\u003e createAsync\u003cTParam, TResult\u003e(AsyncFunc1\u003cTParam, TResult\u003e func,...\r\nstatic RxCommand\u003cvoid, TResult\u003e createAsyncNoParam\u003cTResult\u003e(AsyncFunc\u003cTResult\u003e func,...\r\nstatic RxCommand\u003cTParam, void\u003e createAsyncNoResult\u003cTParam\u003e(AsyncAction1\u003cTParam\u003e action,...\r\nstatic RxCommand\u003cvoid, void\u003e createAsyncNoParamNoResult(AsyncAction action,...\r\n```\r\n\r\n\r\n\u003e IMPORTANT: As of V3.0 `CommandResult` objects are now emitted on the `.results` property and the pure results of the wrapped function on the RxCommand itself. So I switched the two because while working on RxVMS it turned out that I use the pure result much more often. Also the name of `.results` matches much better with `CommandResult`. If you don't want to change your code you can just stay on 2.06 if you don't need any of V 3.0 features. \r\n\r\n\r\nYou can find a tutorial on how to use `RxCommands` in this blog post [Making Flutter more Reactive](https://www.burkharts.net/apps/blog/making-flutter-more-reactive/)\r\n\r\n`RxCommand` is an [_Reactive Extensions_ (Rx)](http://reactivex.io/) based abstraction for event handlers. It is based on `ReactiveCommand` for the [ReactiveUI](https://reactiveui.net/) framework. It makes heavy use of the [RxDart](https://github.com/ReactiveX/rxdart) package.\r\n\r\n\u003ePRs are always welcome ;-)\r\n\r\n\u003e MAYBE BREAKING CHANGE in 2.0.0: Till now the `results` Stream and the `RxCommand` itself behaved like a `BehaviourSubjects`. This can lead to problems when using with Flutter.\r\nFrom now on the default is `PublishSubject`. If you need `BehaviourSubject` behaviour, meaning every new listener gets the last received value, you can set `emitsLastValueToNewSubscriptions = true` when creating `RxCommand`.\r\n\r\nIf you don't know Rx think of it as Dart `Streams` on steroids. `RxCommand` capsules a given handler function that can then be executed by its `execute` method or directly assigned to a widget's handler because it's a callable class. The result of this method is then published through its Stream interface. Additionally it offers Streams for it's current execution state, if the command can be executed and for all possibly thrown exceptions during command execution.\r\n\r\nA very simple example\r\n\r\n```Dart\r\nfinal command = RxCommand.createSync\u003cint, String\u003e((myInt) =\u003e \"$myInt\");\r\n\r\ncommand.listen((s) =\u003e print(s)); // Setup the listener that now waits for events, not doing anything\r\n\r\n// Somwhere else\r\ncommand.execute(10); // the listener will print \"10\"\r\n```\r\n\r\nGetting a bit more impressive:\r\n\r\n```Dart\r\n// This command will be executed everytime the text in a TextField changes\r\nfinal textChangedCommand = RxCommand.createSync((s) =\u003e s);\r\n\r\n// handler for results\r\ntextChangedCommand\r\n  .debounce( new Duration(milliseconds: 500))  // Rx magic: make sure we start processing \r\n                                               // only if the user make a short pause typing \r\n    .listen( (filterText)\r\n    {\r\n      updateWeatherCommand.execute( filterText); // I could omit he execute because RxCommand is a callable class but here it \r\n                                                  //  makes the intention clearer\r\n    });  \r\n\r\n```\r\n\r\n\r\n## Getting Started\r\n\r\nAdd to your `pubspec.yaml` dependencies to `rxdart` and `rx_command`.  \r\n\r\nAn `RxCommand` is a generic class of type `RxCommand\u003cTParam, TRESULT\u003e` where `TPARAM` is the type of data that is passed when calling `execute` and `TResult` denotes the return type of the handler function. To signal that a handler doesn't take a parameter or returns a `null` value use `void` as type. \r\nEven if you create a `RxCommand\u003cvoid,void\u003e` you will receive a `null` value when the wrapped function finishes so you can listen for the successful completion.\r\n\r\nAn example of the declaration from the included sample App\r\n\r\n```Dart\r\nRxCommand\u003cString,List\u003cWeatherEntry\u003e\u003e  updateWeatherCommand;\r\nRxCommand\u003cbool,bool\u003e  switchChangedCommand;\r\n```\r\n\r\n`updateWeatherCommand` expects a handler that takes a `String` as parameter and returns a `List\u003cWeatherEntry\u003e`. `switchChangedCommand` expects and returns a `bool` value \r\n\r\n### Creating RxCommands\r\n\r\n For the different variations of possible handler methods RxCommand offers several factory methods for synchronous and asynchronous handlers. They look like this.\r\n\r\n```Dart\r\n  /// Creates  a RxCommand for a synchronous handler function with no parameter and no return type \r\n  /// `action`: handler function\r\n  /// `canExecute` : Stream that can be used to enable/disable the command based on some other state change\r\n  /// if omitted the command can be executed always except it's already executing\r\n  static RxCommand\u003cvoid, void\u003e createSyncNoParamNoResult(Action action,[Stream\u003cbool\u003e canExecute])\r\n```\r\n\r\nThere are these variants:\r\n\r\n```Dart\r\nstatic RxCommand\u003cTParam, TResult\u003e createSync\u003cTParam, TResult\u003e(Func1\u003cTParam, TResult\u003e func,...\r\nstatic RxCommand\u003cvoid, TResult\u003e createSyncNoParam\u003cTResult\u003e(Func\u003cTResult\u003e func,...\r\nstatic RxCommand\u003cTParam, void\u003e createSyncNoResult\u003cTParam\u003e(Action1\u003cTParam\u003e action,...\r\nstatic RxCommand\u003cvoid, void\u003e createSyncNoParamNoResult(Action action,...\r\n\r\nstatic RxCommand\u003cTParam, TResult\u003e createAsync\u003cTParam, TResult\u003e(AsyncFunc1\u003cTParam, TResult\u003e func,...\r\nstatic RxCommand\u003cvoid, TResult\u003e createAsyncNoParam\u003cTResult\u003e(AsyncFunc\u003cTResult\u003e func,...\r\nstatic RxCommand\u003cTParam, void\u003e createAsyncNoResult\u003cTParam\u003e(AsyncAction1\u003cTParam\u003e action,...\r\nstatic RxCommand\u003cvoid, void\u003e createAsyncNoParamNoResult(AsyncAction action,...\r\n```\r\n\r\nPlease check the API docs for detailed description of all parameters\r\n\r\n#### createFromStream\r\n\r\n  Creates  a RxCommand from an \"one time\" Stream. This is handy if used together with a Stream generator function.  \r\n  `provider`: provider function that returns a new `Stream` that will be subscribed on the call of [execute]\r\n  `canExecute` : Stream that can be used to enable/disable the command based on some other state change\r\n  If omitted the command can be executed always except it's already executing\r\n\r\n```Dart\r\n  static RxCommand\u003cTParam, TResult\u003e createFromStream\u003cTParam, TResult\u003e(StreamProvider\u003cTParam, TResult\u003e provider, [Stream\u003cbool\u003e canExecute])\r\n```\r\n\r\nYou can pass in an additional `Stream\u003cbool\u003e` as `canExceute` that determines if command can be executed. \r\n\r\n#### Example for `canExceute`\r\n\r\nThe sample App contains a `Switch` widget that enables/disables the update command. The switch itself is bound to the `switchChangedCommand` that's result is then used as `canExcecute` of the `updateWeatherCommand`:\r\n\r\n```Dart\r\nswitchChangedCommand = RxCommand.createSync\u003cbool,bool\u003e((b)=\u003eb);\r\n\r\n// We pass the result of switchChangedCommand as canExecute Stream to the upDateWeatherCommand\r\nupdateWeatherCommand = RxCommand.createAsync\u003cString,List\u003cWeatherEntry\u003e\u003e(update,switchChangedCommand.results);\r\n```\r\n\r\nAs the _Update_ `Button`'s building is based on a `StreamBuilder`that listens on the `canExecute` Stream of the `updateWeatherCommand` the buttons enabled/disabled state gets automatically updated when the `Switch's` state changes\r\n\r\n\r\n#### Error handling with RxCommands\r\nBy default all exceptions thrown by the wrapped function will be caught and swallowed. If you want to react on the, you can listen on the `thrownException` property.\r\nIf you want to force RxCommand not to catch Exceptions set `throwExceptions=true`.\r\n\r\n\r\n### Using RxCommands in a Flutter App\r\n\r\n`RxCommand` is typically used in a ViewModel of a Page, which is made accessible to the Widgets via an `InheritedWidget` or `GetIt`. Its `execute`method can then directly be assigned as event handler of the Widgets.\r\n\r\nThe `result` of the command is best used with a `StreamBuilder` or inside a `StatefulWidget`.\r\n\r\nBy subscribing (listening) to the `isExecuting` property of a RxCommand you can react on any execution state change of the command. E.g. show a spinner while the command is running.\r\n\r\nBy subscribing to the `canExecute` property of a RxCommand you can react on any state change of the executability of the command. Like changing the appearance of a Button.\r\n\r\nAs RxCommand is a callable class you can assign it directly to handler functions of Flutter widgets like:\r\n\r\n```Dart\r\nnew TextField(onChanged: TheViewModel.of(context).textChangedCommand,)\r\n```\r\n\r\n#### Listening for CommandResults\r\n\r\nThe original `ReactiveCommand` from _ReactiveUI_ separates the state information of the command into four Streams (`result, thrownExceptions, isExecuting, canExecute`) this works great in an environment that doesn't rebuild the whole screen on state change. Flutter it's often desirable when working with a `StreamBuilder` to have all this information at one place so that you can decide what to display depending on the returned state. Therefore `RxCommand` offer the `.results` Stream emitting `CommandResult`objects:\r\n\r\n```Dart\r\nclass CommandResult\u003cT\u003e\r\n{\r\n  final T         data;\r\n  final dynamic error;\r\n  final bool      isExecuting;\r\n\r\n  const CommandResult(this.data, this.error, this.isExecuting);\r\n\r\n  bool get hasData =\u003e data != null;\r\n  bool get hasError =\u003e error != null;  \r\n}\r\n```\r\n\r\n`isExecuting` will issue a `bool` value on each state change. Even if you subscribe to a newly created command it will issue `false`. When listening for `CommandResult` this normally doesn't make sense, so no initial `CommandResult` will be emitted.\r\nIf you want to get an initial Result with `data==null, error==null, isExceuting==false` pass\r\n`emitInitialCommandResult=true` when creating a command.\r\n\r\n### Accessing the last result\r\n\r\n`RxCommand.lastResult` gives you access to the last successful result of the commands execution.\r\n\r\nIf you want to get the last result included in the `CommandResult` events while executing or in case of and error you can pass `emitInitialCommandResult=true` when creating the command. \r\n\r\nIf you want to assign an initialValue to `.lastResult` e.g. if you use it with a `StreamBuilder's` `initialData` you can pass it with the `initialLastResult` parameter when creating the command.\r\n\r\n\r\n### Disposing subscriptions (listeners)\r\nWhen subscribing to an Stream with `.listen` you should store the returned `StreamSubscription` and call `.cancel` on it if you want to cancel this subscription to a later point or if the object where the subscription is made is getting destroyed to avoid memory leaks.\r\n`RxCommand` has a `dispose` function that will cancel all active subscriptions on its Streams. Calling `dispose`before a command gets out of scope is a good practise.\r\n\r\n## Exploring the sample App \r\n\r\nThe best way to understand how `RxCommand` is used is to look at the supplied sample app which is a simple app that queries a REST API for weather data.\r\n\r\n### The ViewModel\r\n\r\nIt follow the MVVM design pattern so all business logic is bundled in the `WeatherViewModel` class in `weather_viewmodel.dart`.\r\n\r\nIt is made accessible to the Widgets by using an [InheritedWidget](https://docs.flutter.io/flutter/widgets/InheritedWidget-class.html) which is defined in main.dart and returns and instance of `WeatherViewModel`when used like `TheViewModel.of(context)`\r\n\r\nThe view model publishes two commands \r\n\r\n* `updateWeatherCommand` which makes a call to the weather API and filters the result based on a string that is passed to execute. Its result will be bound to a `StreamBuilder`in your View.\r\n* `switchChangedCommand` which will be bound to a `Switch` widget to enable/disable the `updateWeatherCommand.\r\n\r\n\r\n### The View\r\n\r\n`main.dart` creates the ViewModel and places it at the very base of the app`s widget tree.\r\n\r\n`homepage.dart` creates a `Column` with a \r\n\r\n* `TextField` where you can enter a filter text which binds to the ViewModels `textChangedCommand`.\r\n\r\n* a middle block which can either be a `ListView` (`WeatherListView`) or a busy spinner. It is created by a `StreamBuilder` which listens to \u003cbr/\u003e `TheViewModel.of(context).updateWeatherCommand.isExecuting`\u003cbr/\u003e\r\n* A row with the Update `Button` and a `Switch` that toggles if an update should be possible or not by binding to `TheViewModel.of(context).switchChangedCommand)`. To change the enabled state of the button the button is build by a `StreamBuilder` that listens to the  `TheViewModel.of(context).updateWeatherCommand.canExecute` \r\n\r\n`listview.dart` implements `WeatherListView` which consists again of a StreamBuilder which updates automatically by listening on `TheViewModel.of(context).updateWeatherCommand.results`\r\n\r\n\r\n## Making live easier with RxCommandListeners\r\n\r\nIf you want to react on more than one Stream of one command the listening and freeing of multiple of subscriptions makes the code less readable and you have to be careful not to forget to cancel all of them.\r\n\r\n`RxCommandListener` makes this handling much easier. Its constructor takes a command and direct handler functions for the different state changes:\r\n\r\n```Dart\r\nclass RxCommandListener\u003cTParam, TResult\u003e {\r\n  final RxCommand\u003cTParam, TResult\u003e command;\r\n\r\n  // Is called on every emitted value of the command\r\n  final void Function(TResult value) onValue;\r\n  // Is called when isExceuting changes \r\n  final void Function(bool isBusy) onIsBusyChange;\r\n  // Is called on exceptions in the wrapped command function\r\n  final void Function(dynamic ex) onError;\r\n  // Is called when canExecute changes\r\n  final void Function(bool state) onCanExecuteChange;\r\n  // is called with the vealue of the .results Stream of the command\r\n  final void Function(CommandResult\u003cTResult\u003e result) onResult;\r\n\r\n  // to make the handling of busy states even easier these are called on their respective states \r\n  final void Function() onIsBusy;\r\n  final void Function() onNotBusy;\r\n\r\n  // optional you can directly pass in a debounce duration for the values of the command\r\n  final Duration debounceDuration;\r\n\r\nRxCommandListener(this.command,{    \r\n  this.onValue,\r\n  this.onIsBusyChange,\r\n  this.onIsBusy,\r\n  this.onNotBusy,\r\n  this.onError,\r\n  this.onCanExecuteChange,\r\n  this.onResult,\r\n  this.debounceDuration,}\r\n)\r\n\r\n void dispose(); \r\n```  \r\n\r\nYou don't have to pass all handler functions. they all are optional so you can just pass the ones you need. You only have to `dispose` the `RxCommandListener` in your `dispose` function and it will cancel all internally uses subscriptions.\r\n\r\nLet's compare the same code with and without `RxCommandListener` in some real app code. The `selectAndUploadImageCommand` here is used in a chat screen where the user can upload images to the chat. When the command is called an `ImagePicker` dialog is shown and after successful selection of an image the image is uploaded. On completion of the upload the command returns the storage location  of the image so that a new image chat entry can be created.\r\n\r\n```Dart\r\n_selectImageCommandSubscription = sl\r\n      .get\u003cImageManager\u003e()\r\n      .selectAndUploadImageCommand\r\n      .listen((imageLocation) async {\r\n    if (imageLocation == null) return;\r\n    // this calls the execute method of the command\r\n    sl.get\u003cEventManager\u003e().createChatEntryCommand(new ChatEntry(\r\n            event: widget.event,\r\n            isImage: true,\r\n            content: imageLocation.downloadUrl,\r\n          ));\r\n    });\r\n_selectImageIsExecutingSubscription = sl\r\n      .get\u003cImageManager\u003e()\r\n      .selectAndUploadImageCommand\r\n      .isExecuting\r\n      .listen((busy) {\r\n    if (busy) {\r\n      MySpinner.show(context);\r\n    } else {\r\n      MySpinner.hide();\r\n    }\r\n  });\r\n_selectImageErrorSubscription = sl\r\n      .get\u003cImageManager\u003e()\r\n      .selectAndUploadImageCommand\r\n      .thrownExceptions\r\n      .listen((ex) =\u003e showMessageDialog(context, 'Upload problem',\r\n          \"We cannot upload your selected image at the moment. Please check your internet connection\"));\r\n```\r\n\r\nto\r\n\r\n```Dart\r\nselectImageListener = RxCommandListener(\r\n    command: sl.get\u003cImageManager\u003e().selectAndUploadImageCommand,\r\n    onValue: (imageLocation) async {\r\n      if (imageLocation == null) return;\r\n\r\n      sl.get\u003cEventManager\u003e().createChatEntryCommand(new ChatEntry(\r\n            event: widget.event,\r\n            isImage: true,\r\n            content: imageLocation.downloadUrl,\r\n          ));\r\n    },\r\n    onIsBusy: () =\u003e MySpinner.show(context),\r\n    onNotBusy: MySpinner.hide,\r\n    onError: (ex) =\u003e showMessageDialog(context, 'Upload problem',\r\n        \"We cannot upload your selected image at the moment. Please check your internet connection\"));\r\n```\r\n\r\nAs a rule of thumb I would only use an RxCommandListener if I want to listen to more than one Stream.\r\n\r\n\r\n\r\n\r\n\r\n\r\n## Mocking RxCommands\r\n\r\nWhen writing UI Tests with Flutter its often better not to work with the real commands in the ViewModel but to use a `MockCommand` to have better control over the data a command receives and emits.\r\n\r\nFor this the `MockCommand` class is for. It behaves almost like a normal `RxCommand`\r\n\r\nIt's created by\r\n\r\n```Dart\r\n/// Factory constructor that can take an optional Stream to control if the command can be executet\r\nfactory MockCommand({Stream\u003cbool\u003e canExecute} )\r\n```\r\n\r\nYou don't pass a handler function because this should be controlled from the outside.\r\nTo control the outcome of the Command execution you can inspect these properties:\r\n\r\n```Dart\r\n/// the last value that was passed when execute or the command directly was called\r\nTParam lastPassedValueToExecute;\r\n\r\n/// Number of times execute or the command directly was called\r\nint executionCount = 0; \r\n```\r\n\r\nTo simulate a certain data output after calling the command use:\r\n\r\n```Dart\r\n/// to be able to simulate any output of the command when it is called you can here queue the output data for the next exeution call\r\nqueueResultsForNextExecuteCall(List\u003cCommandResult\u003cTResult\u003e\u003e values)\r\n```\r\n\r\nTo execute the command you can either call the command instance directly or call `execute`\r\n\r\n```Dart\r\n/// Can either be called directly or by calling the object itself because RxCommands are callable classes\r\n/// Will increase [executionCount] and assign [lastPassedValueToExecute] the value of [param]\r\n/// If you have queued a result with [queueResultsForNextExecuteCall] it will be copies tho the output stream.\r\n/// [isExecuting], [canExceute] and [results] will work as with a real command.  \r\nexecute([TParam param])\r\n```\r\n\r\nHere an example from the `rx_widgets` example App\r\n\r\n```Dart\r\ntestWidgets('Tapping update button updates the weather', (tester) async {\r\n  final model = new MockModel(); // using mockito\r\n  final command = new MockCommand\u003cString,List\u003cWeatherEntry\u003e\u003e();\r\n    final widget = new ModelProvider(\r\n                          model: model,\r\n                          child: new MaterialApp(home: new HomePage()),\r\n                      );\r\n\r\n  // to make the mocked model use the MockCommand instance. \r\n  when(model.updateWeatherCommand).thenReturn(command);\r\n  // if your App does not only access the command but also calls\r\n  // it directly you have to register the call too:\r\n  when(model.updateWeatherCommand()).thenAnswer((_)=\u003ecommand());\r\n\r\n  command.queueResultsForNextExecuteCall([CommandResult\u003cList\u003cWeatherEntry\u003e\u003e(\r\n              [WeatherEntry(\"London\", 10.0, 30.0, \"sunny\", 12)],null, false)]);\r\n\r\n  expect(command.results, emitsInOrder([ crm(null, false, false), // default value that will be emited at startup \r\n                                 crm([WeatherEntry(\"London\", 10.0, 30.0, \"sunny\", 12)], // data\r\n                                  false, false) ]));\r\n\r\n  await tester.pumpWidget(widget); // Build initial State\r\n  await tester.pump(); // Build after Stream delivers value\r\n\r\n  await tester.tap(find.byKey(AppKeys.updateButtonEnabled));\r\n\r\n\r\n});\r\n```    \r\n\r\n\r\nTo verify the changing states of the command e.g. to check if linked UI controls are created or in a certain state use:\r\n\r\n\r\n```Dart\r\n/// For a more fine grained control to simulate the different states of an `RxCommand`\r\n/// there are these functions\r\n/// [startExecution] will issue a `CommandResult` with\r\n/// data: null\r\n/// error: null\r\n/// isExecuting : true\r\nvoid startExecution()\r\n\r\n/// [endExecutionWithData] will issue a `CommandResult` with\r\n/// data: [data]\r\n/// error: null\r\n/// isExecuting : false\r\nvoid endExecutionWithData(TResult data)\r\n\r\n/// [endExecutionWithData] will issue a `CommandResult` with\r\n/// data: null\r\n/// error: Exeption([message])\r\n/// isExecuting : false\r\nvoid endExecutionWithError(String message)\r\n\r\n/// [endExecutionWithData] will issue a `CommandResult` with\r\n/// data: null\r\n/// error: null\r\n/// isExecuting : false\r\nvoid endExecutionNoData()\r\n```\r\n\r\nAlso an example from `rx_widgets`\r\n\r\n```Dart\r\ntestWidgets('Shows a loading spinner and disables the button while executing \r\n            and shows the ListView on data arrival', (tester) async {\r\n  final model = new MockModel();\r\n  final command = new MockCommand\u003cString,List\u003cWeatherEntry\u003e\u003e();\r\n  final widget = new ModelProvider(\r\n                        model: model,\r\n                        child: new MaterialApp(home: new HomePage()),\r\n                      );\r\n\r\n  // Link MockCommand instance to mocked field in model\r\n  when(model.updateWeatherCommand).thenReturn(command);\r\n\r\n\r\n  await tester.pumpWidget(widget);// Build initial State\r\n  await tester.pump(); \r\n\r\n  expect(find.byKey(AppKeys.loadingSpinner), findsNothing);\r\n  expect(find.byKey(AppKeys.updateButtonDisabled), findsNothing);\r\n  expect(find.byKey(AppKeys.updateButtonEnabled), findsOneWidget);\r\n  expect(find.byKey(AppKeys.weatherList), findsNothing);\r\n  expect(find.byKey(AppKeys.loaderError), findsNothing);\r\n  expect(find.byKey(AppKeys.loaderPlaceHolder), findsOneWidget);\r\n\r\n\r\n  command.startExecution();\r\n  await tester.pump(); \r\n  // because there are two streams involded it seems we have to pump \r\n  // twice so that both streambuilders can work\r\n  await tester.pump();  \r\n\r\n  expect(find.byKey(AppKeys.loadingSpinner), findsOneWidget);\r\n  expect(find.byKey(AppKeys.updateButtonDisabled), findsOneWidget);\r\n  expect(find.byKey(AppKeys.updateButtonEnabled), findsNothing);\r\n  expect(find.byKey(AppKeys.weatherList), findsNothing);\r\n  expect(find.byKey(AppKeys.loaderError), findsNothing);\r\n  expect(find.byKey(AppKeys.loaderPlaceHolder), findsNothing);\r\n\r\n  command.endExecutionWithData([new WeatherEntry(\"London\", 10.0, 30.0, \"sunny\", 12)]);\r\n  await tester.pump(); // Build after Stream delivers value\r\n\r\n  expect(find.byKey(AppKeys.loadingSpinner), findsNothing);\r\n  expect(find.byKey(AppKeys.updateButtonDisabled), findsNothing);\r\n  expect(find.byKey(AppKeys.updateButtonEnabled), findsOneWidget);\r\n  expect(find.byKey(AppKeys.weatherList), findsOneWidget);\r\n  expect(find.byKey(AppKeys.loaderError), findsNothing);\r\n  expect(find.byKey(AppKeys.loaderPlaceHolder), findsNothing);\r\n});\r\n```\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffluttercommunity%2Frx_command","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffluttercommunity%2Frx_command","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffluttercommunity%2Frx_command/lists"}