w_module 2.0.3

  • README.md
  • Installing
  • Versions
  • 17

w_module

Pub Build Status codecov.io documentation

Base module classes with a well defined lifecycle for modular Dart applications.


Overview

w_module Boundaries Diagram

w_module implements a module encapsulation and lifecycle pattern for Dart that interfaces well with the application architecture defined in the w_flux library. w_module defines the public interface for a module and is in no way prescriptive as to how module internals are defined, though the w_flux pattern is recommended. w_module defines how data should flow in and out of a module, how renderable UI is exposed to consumers, and establishes a common module lifecycle that facilitates dynamic loading / unloading of complex module hierarchies.


Module Structure

A w_module Module encapsulates a well-scoped logical unit of functionality and exposes a discrete public interface for consumers. It extends LifecycleModule to ensure that its load / unload processes adhere to a well-defined lifecycle. The public interface of a Module is comprised of api, events, and components:

  • The api class exposes public methods that can be used to mutate or query module data.
  • The events class exposes streams that can be listened to for notification of internal module state change.
  • The components class exposes react-dart compatible UI components that can be used to render module data.

Though the class based Module convention is somewhat arbitrary, exposing api, events, and components via aggregate classes simplifies consumption and improves the discoverability of the Module's public interface.

// bare bones module definition

DispatchKey sampleDispatchKey = new DispatchKey('sampleModule');

class SampleModule extends Module {

  final String name = 'SampleModule';

  SampleApi _api;
  SampleApi get api => _api;

  SampleEvents _events;
  SampleEvents get events => _events;

  SampleComponents _components;
  SampleComponents get components => _components;

  SampleModule() {
    _api = new SampleApi();
    _events = new SampleEvents(sampleDispatchKey);
    _components = new SampleComponents();
  }
}

If using w_module with w_flux internals, api, events, and components should be internally initialized with access to the module's actions and stores.

// module definition with w_flux internals

DispatchKey sampleDispatchKey = new DispatchKey('sampleModule');

class SampleModule extends Module {

  final String name = 'SampleModule';

  SampleActions _actions;
  SampleStore _store;

  SampleApi _api;
  SampleApi get api => _api;

  SampleEvents _events;
  SampleEvents get events => _events;

  SampleComponents _components;
  SampleComponents get components => _components;

  SampleModule() {
    _actions = new SampleActions();
    _events = new SampleEvents();
    _store = new SampleStore(_actions, _events, sampleDispatchKey);
    _components = new SampleComponents(_actions, _store);
    _api = new SampleApi(_actions, _store);
  }
}

API

A Module's api member should expose all public methods that a consumer can use to mutate module state (methods) or query existing module state (getters). api is initially null. If a module exposes a public api, this should be overridden to provide a class defined specifically for the module.

// module api definition

class SampleApi {

  SampleApi();

  setSampleValue(String newValue) {
    ...
  }

  String get sampleValue => ...;
}
// module api consumption

sampleModule.api.setSampleValue(...);

String sampleValue = sampleModule.api.sampleValue;

If using w_module with w_flux internals, module mutation methods should usually dispatch existing actions available within the module. This ensures that the internal unidirectional data flow is maintained, regardless of the source of the mutation (e.g. external api or internal UI). Likewise, module methods that expose internal state should usually use existing getter methods available on stores within the module.

// module api definition with w_flux internals

class SampleApi {

  SampleActions _actions;
  SampleStore _store;

  SampleApi(this._actions, this._store);

  setSampleValue(String newValue) {
    _actions.setSampleValue(newValue);
  }

  String get sampleValue => _store.sampleValue;
}

Events

A Module's events member should expose all public streams that a consumer can listen to for notification of internal state changes. events is initially null. If a module exposes public events, this should be overridden to provide a class defined specifically for the module.

A Module's events are intended to be 'read-only'. Though events are exposed for listening by external consumers, they should only be dispatched from within the Module. To enforce this limitation, a dispatch key is required to instantiate the event stream. The same dispatch key must subsequently be used to dispatch all events on the stream. Keeping the dispatch key private in the Module internals effectively prevents uncontrolled external dispatch.

// module events definition

DispatchKey sampleDispatchKey = new DispatchKey('sampleModule');

class SampleEvents {
  final Event<String> valueChanged = new Event(sampleDispatchKey);
}
// module events dispatch

_events.valueChanged(_sampleValue, sampleDispatchKey);
// module events consumption

sampleModule.events.valueChanged.listen((newValue) {
  ...
});

If using w_module with w_flux internals, events should usually be dispatched by internal stores immediately prior to a corresponding trigger dispatch. events should NOT be dispatched directly by UI components or in immediate response to actions. This ensures that the internal unidirectional data flow is maintained and external events represent confirmed internal state changes.

// module events dispatch with w_flux internals

class SampleStore extends Store {

  String _sampleValue = 'something';

  RandomColorEvents _events;
  DispatchKey _dispatchKey;

  SampleActions _actions;

  SampleStore(SampleActions this._actions, SampleEvents this._events, DispatchKey this._dispatchKey) {
    ...
    _actions.setSampleValue.listen(_setSampleValue);
  }

  _setSampleValue(String newValue) {
    _sampleValue = newValue;
    _events.valueChanged(_sampleValue, _dispatchKey);
    trigger();
  }
}

To assist in properly disposing of Event instances, w_module provides an EventsCollection base class that extends Disposable from the w_common package with an additional manageEvent() method. Colocating related events in an EventsCollection makes it trivial to close all Event instances by disposing the EventsCollection instance.

final key = new DispatchKey('example');

class ExampleEvents extends EventsCollection {
  final Event<String> eventA = new Event<String>(key);
  final Event<String> eventB = new Event<String>(key);

  ExampleEvents() : super(key) {
    [
      eventA,
      eventB,
    ].forEach(manageEvent);
  }
}

main() async {
  final eventsCollection = new EventsCollection();
  await eventsCollection.dispose();
  // All Events on the collection should now be closed.
}

Components

A Module's components member should expose all react-dart compatible UI component factories that a consumer can use to render module data. components is initially null. If a module exposes public components, this should be overridden to provide a class defined specifically for the module.

By convention, the custom components class should extend the included ModuleComponents class to ensure that the default UI component is available via the module.components.content() method.

// module components definition

class SampleComponents implements ModuleComponents {

  content() => SampleComponent(...);
}
// module components consumption

react.render(sampleModule.components.content(),
    html.querySelector('#content-container'));

If using w_module with w_flux internals, components methods should usually return UI component factories that have been internally initialized with the proper actions and stores props. This ensures full functionality of the components without any external exposure of the requisite internal actions and stores.

// module components definition with w_flux internals

class SampleComponents implements ModuleComponents {

  SampleActions _actions;
  SampleStore _store;

  SampleComponents(this._actions, this._store);

  content() => SampleComponent({'actions': _actions, 'store': _store});
}

Module Lifecycle

w_module implements a simple Module lifecycle that ensures that modules adhere to a predictable loading and unloading pattern. Using Module as the basis for all modules in an application ensures that this simple pattern will extrapolate predictably across complex module hierarchies.

Many examples of Module lifecycle behavior and manipulation can be found in the Multiple Module Panel example.

Lifecycle Methods

Module exposes five lifecycle methods that external consumers should use to trigger loading and unloading behavior. These methods can return an error or exception thrown by their respective lifecycle handler methods. This allows dependencies on a Module to respond to failures that occur within the overridden lifecycle behavior.

MethodDescription
loadTriggers loading of a Module. Internally, this executes the module's onLoad method and dispatches the willLoad and didLoad events. Returns a future that completes once the module has finished loading.
suspendSuspends the module and all child modules. While suspended modules should make themselves lightweight and avoid making network requests.
resumeBrings the module and all child modules out of suspension. Upon resuming, modules should go back to business as usual.
shouldUnloadReturns the unloadable state of the Module and its child modules as a ShouldUnloadResult. Internally, this executes the module's onShouldUnload method.
unloadTriggers unloading of a Module and all of its child modules. Internally, this executes the module's shouldUnload method, and, if that completes successfully, executes the module's onUnload method. If unloading is rejected, this method will complete with an error. The rejected error will not be added to the didUnload lifecycle event stream.

Lifecycle of a LifecycleModule

The graphic above illustrates legal lifecycle state transitions. Any state transition that is not defined will throw a StateError. No-op transitions are illustrated with blue arrows. Calling the lifecycle method when the module is already in the given state will result in a logger warning. If a no-op is performed on a transitioning state the pending transition future is returned.

Lifecycle Events

Module also exposes lifecycle event streams that an external consumer can listen to. If any corresponding lifecycle handler method throws an exception or error it will be added to the corresponding stream. This allows dependencies on a Module to provide an onError function to handle recovering from a failure within the module implementation.

EventDescription
willLoadDispatched at the beginning of the module's load logic.
didLoadDispatched at the end of the module's load logic.
willSuspendDispatched at the beginning of the module's suspend logic.
didSuspendDispatched at the end of the module's suspend logic.
willResumeDispatched at the beginning of the module's resume logic.
didResumeDispatched at the end of the module's resume logic.
willUnloadDispatched at the beginning of the module's unload logic.
didUnloadDispatched at the end of the module's unload logic.

Lifecycle Customization

Internally, Module contains methods that can be overridden to customize module lifecycle behavior. Any error or exception thrown by these overloaded lifecycle methods will be added to their corresponding lifecycle event stream. This error will be returned to the caller of the corresponding lifecycle method.

MethodDescription
onLoadExecuting during the module's load logic. Custom logic for initializing child modules, service access, event listeners, etc. should be implemented here. Deferred module loading behavior can also be hidden from consumers via this method.
onSuspendExecuted during the module's suspend logic. This method should be used to modify module behavior while suspended.
onResumeExecuted during the module's resume logic. This method should be used to put the module back into its normal mode of operation.
onShouldUnloadExecuted during the module's shouldUnload logic. Custom logic that blocks module unloading under certain conditions should be implemented here.
onUnloadExecuted during the module's unload logic. Custom module clean up logic should be implemented here. Unfortunately, the nature of web browsers is such that module unload logic is not guaranteed to be executed under all conditions (browser or tab close), so mission critical logic should not reside here.

Module Hierarchies

Module also supports hierarchical application of the standard lifecycle through child modules:

MethodDescription
loadChildModuleLoads a child module and registers it with the current module for lifecycle management.
willLoadChildModuleDispatched at the beginning of the child module's load logic.
didLoadChildModuleDispatched at the end of the child module's load logic.

Getters

GetterDescription
childModulesAn iterable of child modules.
isLoadedA boolean that indicates whether the module is current loaded.
isSuspendedA boolean that indicates whether the module is currently suspended. This will always be false when the module is not loaded.

Disposal

Module extends Disposable from the w_common package which provides some additional facilities for memory management. This means that you can leverage any of the disposable management APIs like listenToStream() or manageDisposable() within your Module. Additionally, it means that Modules can be disposed via dispose(). While this is similar to unload(), there is a key difference:

unload() will attempt to unload a Module, but may fail to complete in two scenarios:

  • if the unload is canceled via shouldUnload()
  • if the unload fails due to an uncaught exception in onUnload()

If the unload succeeds, then disposal will happen implicitly.

dispose() will attempt to unload the Module first (unless it has never been loaded, in which case it will go straight to disposal), but will force disposal regardless of the outcome of the unload step.

In most scenarios, consumers should use unload() either directly or indirectly via the other lifecycle management APIs like loadChildModule().

Calling dispose() should be reserved for scenarios where you know the Module has not been loaded, but still needs to be disposed, or when you need to force the disposal of the Module regardless of its state and do not care about the Modules ability to prevent its unloading. Unit tests are a likely candidate for this usage.

Disposal of a LifecycleModule


Examples

Simple examples of w_module usage can be found in the example directory. The example README includes instructions for building / running them.


Development

This project leverages the dart_dev package for most of its tooling needs, including static analysis, code formatting, running tests, collecting coverage, and serving examples. Check out the dart_dev readme for more information.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  w_module: ^2.0.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:w_module/w_module.dart';
  
Version Uploaded Documentation Archive
2.0.3 Oct 16, 2018 Go to the documentation of w_module 2.0.3 Download w_module 2.0.3 archive
2.0.2 Oct 8, 2018 Go to the documentation of w_module 2.0.2 Download w_module 2.0.2 archive
2.0.1 Sep 24, 2018 Go to the documentation of w_module 2.0.1 Download w_module 2.0.1 archive
2.0.0 Sep 13, 2018 Go to the documentation of w_module 2.0.0 Download w_module 2.0.0 archive
1.6.2 Oct 8, 2018 Go to the documentation of w_module 1.6.2 Download w_module 1.6.2 archive
1.6.1 Sep 25, 2018 Go to the documentation of w_module 1.6.1 Download w_module 1.6.1 archive
1.6.0 Sep 11, 2018 Go to the documentation of w_module 1.6.0 Download w_module 1.6.0 archive
1.5.2 Aug 7, 2018 Go to the documentation of w_module 1.5.2 Download w_module 1.5.2 archive
1.5.1 Jan 10, 2018 Go to the documentation of w_module 1.5.1 Download w_module 1.5.1 archive
1.5.0 Oct 27, 2017 Go to the documentation of w_module 1.5.0 Download w_module 1.5.0 archive

All 26 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
33
Health:
Code health derived from static analysis. [more]
0
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
0
Overall:
Weighted score of the above. [more]
17
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Support Dart 2 in pubspec.yaml.

The SDK constraint in pubspec.yaml doesn't allow the Dart 2.0.0 release. For information about upgrading it to be Dart 2 compatible, please see https://www.dartlang.org/dart-2#migration.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.9.0 <2.0.0