Open born2net opened 8 years ago
An Observable is just a more ordered version of a thunk. The way folks use thunks in Redux is typically to dispatch 1 or more actions, possibly async, and end in success or error. But a thunk is in fact a Javascript executable function, not simply a data structure. Its better to use a more specific type of structure.
An Observable has behavior over time, like a highly crafted async JS function with callbacks, but the semantics for dealing with it are more tightly defined. In particular, exceptions are turned into onError
events.
var o = new Observable(observer =>
o.onNext({type: 'BEGIN'})
fetch('url')
.then(r => o.onNext({type: 'SUCCESS', payload: r}))
.catch(e => o.onError({type: 'FAILED', payload: e}))
)
store.dispatch(o)
// OR, using RxJS magical stream operators which allow flexible stream converstion
store.dispatch(o.timeout(2500))
So that's what dispatching a (handcrafted) Observable would look like. You can also create Observables from Promises, Arrays, thunks, etc.. So in fact a possibly-terminating series of events is an excellent model for async actions.
Would love to see more examples on usage to replace Thunks for example and other use cases...
regards
Sean