Affect the order/priority of subscription callbacks in ReSwift
(Reply to "Any way to control the priority of subscription callbacks?" https://github.com/ReSwift/ReSwift/issues/404)
ReSwift does not guarantee any subscription callback order. Since ReSwift uses an unordered
Set as its subscription store, there's no reliable way to know when a subscription is invoked.
This implementation detail is hidden by design. If you find yourself wanting to affect the order of subscription callbacks, there's a concept of a sequence waiting to be extracted somehow.
These are the ways out:
- Use object delegation. Have 1 "wrapper" subscriber forward the event to multiple other objects which are themselves not subscribers; the subscriber encapsulates the sequencing.
- Use event sequences (e.g. enum cases) with multiple subscribers each listening to different substates
- Use Middlewares if you want a side effect to happen before/after an action
Encapsulate the sequence in
Subscriber and delegate to the
Network service first, then to the
+-----------+ | State | +-----+-----+ | | v +-----+-----+ | Subscriber| +-----+-----+ | +----------------+ 1) | | 2) +-----v-----+ +------v------+ | Network | | Presenter | | service | | | +-----------+ +-------------+
Encapsulate the sequence in the state itself. A
NetworkRequest enum with multiple states does this for you:
Then you can have multiple subscribers waiting for the value to change to e.g.
.starting to fire off the request.
The order of Middleware is set by the user. Listen for an action in your Middleware, then dispatch a network request from there.
You can also swallow or hold on to actions in the meantime, waiting for the request to complete. The Middleware may use internal caches of actions from request start to completion and to debounce repetetive dispatches, for example.
As a rule of thumb, I use subscribers to change my views and the middleware to apply other kind of side effects. ---Daniel Martín https://github.com/ReSwift/ReSwift/issues/404#issuecomment-479808160