|
5 | 5 | */ |
6 | 6 | 'use strict'; |
7 | 7 |
|
8 | | -var Subscribable = { |
9 | | - Mixin: { |
10 | | - componentWillMount: function() { |
11 | | - this._subscriptions = []; |
12 | | - }, |
13 | | - componentWillUnmount: function() { |
14 | | - this._subscriptions.forEach((subscription) => subscription.remove()); |
15 | | - this._subscriptions = null; |
16 | | - }, |
17 | | - |
18 | | - /** |
19 | | - * Special form of calling `addListener` that *guarantees* that a |
20 | | - * subscription *must* be tied to a component instance, and therefore will |
21 | | - * be cleaned up when the component is unmounted. It is impossible to create |
22 | | - * the subscription and pass it in - this method must be the one to create |
23 | | - * the subscription and therefore can guarantee it is retained in a way that |
24 | | - * will be cleaned up. |
25 | | - * |
26 | | - * @param {EventEmitter} eventEmitter emitter to subscribe to. |
27 | | - * @param {string} eventType Type of event to listen to. |
28 | | - * @param {function} listener Function to invoke when event occurs. |
29 | | - * @param {object} context Object to use as listener context. |
30 | | - */ |
31 | | - addListenerOn: function(eventEmitter, eventType, listener, context) { |
32 | | - this._subscriptions.push( |
33 | | - eventEmitter.addListener(eventType, listener, context) |
34 | | - ); |
| 8 | +/** |
| 9 | + * Subscribable wraps EventEmitter in a clean interface, and provides a mixin |
| 10 | + * so components can easily subscribe to events and not worry about cleanup on |
| 11 | + * unmount. |
| 12 | + * |
| 13 | + * Also acts as a basic store because it records the last data that it emitted, |
| 14 | + * and provides a way to populate the initial data. The most recent data can be |
| 15 | + * fetched from the Subscribable by calling `get()` |
| 16 | + * |
| 17 | + * Advantages over EventEmitter + Subscibable.Mixin.addListenerOn: |
| 18 | + * - Cleaner usage: no strings to identify the event |
| 19 | + * - Lifespan pattern enforces cleanup |
| 20 | + * - More logical: Subscribable.Mixin now uses a Subscribable class |
| 21 | + * - Subscribable saves the last data and makes it available with `.get()` |
| 22 | + * |
| 23 | + * Legacy Subscribable.Mixin.addListenerOn allowed automatic subscription to |
| 24 | + * EventEmitters. Now we should avoid EventEmitters and wrap with Subscribable |
| 25 | + * instead: |
| 26 | + * |
| 27 | + * ``` |
| 28 | + * AppState.networkReachability = new Subscribable( |
| 29 | + * RCTDeviceEventEmitter, |
| 30 | + * 'reachabilityDidChange', |
| 31 | + * (resp) => resp.network_reachability, |
| 32 | + * RKReachability.getCurrentReachability |
| 33 | + * ); |
| 34 | + * |
| 35 | + * var myComponent = React.createClass({ |
| 36 | + * mixins: [Subscribable.Mixin], |
| 37 | + * getInitialState: function() { |
| 38 | + * return { |
| 39 | + * isConnected: AppState.networkReachability.get() !== 'none' |
| 40 | + * }; |
| 41 | + * }, |
| 42 | + * componentDidMount: function() { |
| 43 | + * this._reachSubscription = this.subscribeTo( |
| 44 | + * AppState.networkReachability, |
| 45 | + * (reachability) => { |
| 46 | + * this.setState({ isConnected: reachability !== 'none' }) |
| 47 | + * } |
| 48 | + * ); |
| 49 | + * }, |
| 50 | + * render: function() { |
| 51 | + * return ( |
| 52 | + * <Text> |
| 53 | + * {this.state.isConnected ? 'Network Connected' : 'No network'} |
| 54 | + * </Text> |
| 55 | + * <Text onPress={() => this._reachSubscription.remove()}> |
| 56 | + * End reachability subscription |
| 57 | + * </Text> |
| 58 | + * ); |
| 59 | + * } |
| 60 | + * }); |
| 61 | + * ``` |
| 62 | + */ |
| 63 | + |
| 64 | +var EventEmitter = require('EventEmitter'); |
| 65 | + |
| 66 | +var invariant = require('invariant'); |
| 67 | +var logError = require('logError'); |
| 68 | + |
| 69 | +var SUBSCRIBABLE_INTERNAL_EVENT = 'subscriptionEvent'; |
| 70 | + |
| 71 | + |
| 72 | +class Subscribable { |
| 73 | + /** |
| 74 | + * Creates a new Subscribable object |
| 75 | + * |
| 76 | + * @param {EventEmitter} eventEmitter Emitter to trigger subscription events. |
| 77 | + * @param {string} eventName Name of emitted event that triggers subscription |
| 78 | + * events. |
| 79 | + * @param {function} eventMapping (optional) Function to convert the output |
| 80 | + * of the eventEmitter to the subscription output. |
| 81 | + * @param {function} getInitData (optional) Async function to grab the initial |
| 82 | + * data to publish. Signature `function(successCallback, errorCallback)`. |
| 83 | + * The resolved data will be transformed with the eventMapping before it |
| 84 | + * gets emitted. |
| 85 | + */ |
| 86 | + constructor(eventEmitter, eventName, eventMapping, getInitData) { |
| 87 | + |
| 88 | + this._internalEmitter = new EventEmitter(); |
| 89 | + this._eventMapping = eventMapping || (data => data); |
| 90 | + |
| 91 | + eventEmitter.addListener( |
| 92 | + eventName, |
| 93 | + this._handleEmit, |
| 94 | + this |
| 95 | + ); |
| 96 | + |
| 97 | + // Asyncronously get the initial data, if provided |
| 98 | + getInitData && getInitData(this._handleInitData.bind(this), logError); |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Returns the last data emitted from the Subscribable, or undefined |
| 103 | + */ |
| 104 | + get() { |
| 105 | + return this._lastData; |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Add a new listener to the subscribable. This should almost never be used |
| 110 | + * directly, and instead through Subscribable.Mixin.subscribeTo |
| 111 | + * |
| 112 | + * @param {object} lifespan Object with `addUnmountCallback` that accepts |
| 113 | + * a handler to be called when the component unmounts. This is required and |
| 114 | + * desirable because it enforces cleanup. There is no easy way to leave the |
| 115 | + * subsciption hanging |
| 116 | + * { |
| 117 | + * addUnmountCallback: function(newUnmountHanlder) {...}, |
| 118 | + * } |
| 119 | + * @param {function} callback Handler to call when Subscribable has data |
| 120 | + * updates |
| 121 | + * @param {object} context Object to bind the handler on, as "this" |
| 122 | + * |
| 123 | + * @return {object} the subscription object: |
| 124 | + * { |
| 125 | + * remove: function() {...}, |
| 126 | + * } |
| 127 | + * Call `remove` to terminate the subscription before unmounting |
| 128 | + */ |
| 129 | + subscribe(lifespan, callback, context) { |
| 130 | + invariant( |
| 131 | + typeof lifespan.addUnmountCallback === 'function', |
| 132 | + 'Must provide a valid lifespan, which provides a way to add a ' + |
| 133 | + 'callback for when subscription can be cleaned up. This is used ' + |
| 134 | + 'automatically by Subscribable.Mixin' |
| 135 | + ); |
| 136 | + invariant( |
| 137 | + typeof callback === 'function', |
| 138 | + 'Must provide a valid subscription handler.' |
| 139 | + ); |
| 140 | + |
| 141 | + // Add a listener to the internal EventEmitter |
| 142 | + var subscription = this._internalEmitter.addListener( |
| 143 | + SUBSCRIBABLE_INTERNAL_EVENT, |
| 144 | + callback, |
| 145 | + context |
| 146 | + ); |
| 147 | + |
| 148 | + // Clean up subscription upon the lifespan unmount callback |
| 149 | + lifespan.addUnmountCallback(() => { |
| 150 | + subscription.remove(); |
| 151 | + }); |
| 152 | + |
| 153 | + return subscription; |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Callback for the initial data resolution. Currently behaves the same as |
| 158 | + * `_handleEmit`, but we may eventually want to keep track of the difference |
| 159 | + */ |
| 160 | + _handleInitData(dataInput) { |
| 161 | + var emitData = this._eventMapping(dataInput); |
| 162 | + this._lastData = emitData; |
| 163 | + this._internalEmitter.emit(SUBSCRIBABLE_INTERNAL_EVENT, emitData); |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Handle new data emissions. Pass the data through our eventMapping |
| 168 | + * transformation, store it for later `get()`ing, and emit it for subscribers |
| 169 | + */ |
| 170 | + _handleEmit(dataInput) { |
| 171 | + var emitData = this._eventMapping(dataInput); |
| 172 | + this._lastData = emitData; |
| 173 | + this._internalEmitter.emit(SUBSCRIBABLE_INTERNAL_EVENT, emitData); |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | + |
| 178 | +Subscribable.Mixin = { |
| 179 | + |
| 180 | + /** |
| 181 | + * @return {object} lifespan Object with `addUnmountCallback` that accepts |
| 182 | + * a handler to be called when the component unmounts |
| 183 | + * { |
| 184 | + * addUnmountCallback: function(newUnmountHanlder) {...}, |
| 185 | + * } |
| 186 | + */ |
| 187 | + _getSubscribableLifespan: function() { |
| 188 | + if (!this._subscribableLifespan) { |
| 189 | + this._subscribableLifespan = { |
| 190 | + addUnmountCallback: (cb) => { |
| 191 | + this._endSubscribableLifespanCallbacks.push(cb); |
| 192 | + }, |
| 193 | + }; |
35 | 194 | } |
| 195 | + return this._subscribableLifespan; |
| 196 | + }, |
| 197 | + |
| 198 | + _endSubscribableLifespan: function() { |
| 199 | + this._endSubscribableLifespanCallbacks.forEach(cb => cb()); |
| 200 | + }, |
| 201 | + |
| 202 | + /** |
| 203 | + * Components use `subscribeTo` for listening to Subscribable stores. Cleanup |
| 204 | + * is automatic on component unmount. |
| 205 | + * |
| 206 | + * To stop listening to the subscribable and end the subscription early, |
| 207 | + * components should store the returned subscription object and invoke the |
| 208 | + * `remove()` function on it |
| 209 | + * |
| 210 | + * @param {Subscribable} subscription to subscribe to. |
| 211 | + * @param {function} listener Function to invoke when event occurs. |
| 212 | + * @param {object} context Object to bind the handler on, as "this" |
| 213 | + * |
| 214 | + * @return {object} the subscription object: |
| 215 | + * { |
| 216 | + * remove: function() {...}, |
| 217 | + * } |
| 218 | + * Call `remove` to terminate the subscription before unmounting |
| 219 | + */ |
| 220 | + subscribeTo: function(subscribable, handler, context) { |
| 221 | + invariant( |
| 222 | + subscribable instanceof Subscribable, |
| 223 | + 'Must provide a Subscribable' |
| 224 | + ); |
| 225 | + return subscribable.subscribe( |
| 226 | + this._getSubscribableLifespan(), |
| 227 | + handler, |
| 228 | + context |
| 229 | + ); |
| 230 | + }, |
| 231 | + |
| 232 | + componentWillMount: function() { |
| 233 | + this._endSubscribableLifespanCallbacks = []; |
| 234 | + |
| 235 | + // DEPRECATED addListenerOn* usage: |
| 236 | + this._subscribableSubscriptions = []; |
| 237 | + }, |
| 238 | + |
| 239 | + componentWillUnmount: function() { |
| 240 | + // Resolve the lifespan, which will cause Subscribable to clean any |
| 241 | + // remaining subscriptions |
| 242 | + this._endSubscribableLifespan && this._endSubscribableLifespan(); |
| 243 | + |
| 244 | + // DEPRECATED addListenerOn* usage uses _subscribableSubscriptions array |
| 245 | + // instead of lifespan |
| 246 | + this._subscribableSubscriptions.forEach( |
| 247 | + (subscription) => subscription.remove() |
| 248 | + ); |
| 249 | + this._subscribableSubscriptions = null; |
| 250 | + }, |
| 251 | + |
| 252 | + /** |
| 253 | + * DEPRECATED - Use `Subscribable` and `Mixin.subscribeTo` instead. |
| 254 | + * `addListenerOn` subscribes the component to an `EventEmitter`. |
| 255 | + * |
| 256 | + * Special form of calling `addListener` that *guarantees* that a |
| 257 | + * subscription *must* be tied to a component instance, and therefore will |
| 258 | + * be cleaned up when the component is unmounted. It is impossible to create |
| 259 | + * the subscription and pass it in - this method must be the one to create |
| 260 | + * the subscription and therefore can guarantee it is retained in a way that |
| 261 | + * will be cleaned up. |
| 262 | + * |
| 263 | + * @param {EventEmitter} eventEmitter emitter to subscribe to. |
| 264 | + * @param {string} eventType Type of event to listen to. |
| 265 | + * @param {function} listener Function to invoke when event occurs. |
| 266 | + * @param {object} context Object to use as listener context. |
| 267 | + */ |
| 268 | + addListenerOn: function(eventEmitter, eventType, listener, context) { |
| 269 | + this._subscribableSubscriptions.push( |
| 270 | + eventEmitter.addListener(eventType, listener, context) |
| 271 | + ); |
36 | 272 | } |
37 | 273 | }; |
38 | 274 |
|
|
0 commit comments