I'm new to Flux/React and I'm having a hard time understanding some of the fundamental architecture decisions:
- I know all stores are meant to be singletons, but are they all created at app start, or can the lifetime of a store be smaller, specific to the user's actions?
- Can I have multiple instances of the same store type, each initialized with a different context?
Unfortunately, all the examples I've seen seem too simplistic to answer these questions. Let's start with Facebook's chat app example. There are multiple threads each with messages. MessageStore holds all the messages for the entire app and a method called getAllForThread(id) returns a filtered subset of messages. When a message comes into ANY thread, it emits a change notification that causes the MessageSection react component to re-fetch data (regardless of which thread the user is viewing). This obviously doesn't scale. What if we had 10,000 threads each with lots of message activity? Here's how I decided to solve the issue:
- Each MessageStore is initialized with a thread id.
- Create a singleton MessageStoreFactory that creates and manages MessageStores.
- When the user clicks on a thread, instead of the React component subscribing to a global MessageStore, it asks the MessageStoreFactory for the MessageStore for that specific thread.
- If the factory already has a MessageStore for that thread, it returns it. Otherwise it creates one, kicks off an async task to fetch the initial data for it, and returns it.
- When the React component is torn down (let's say the user navigates away from it), it notifies the Factory that it's all done with the Store. Using reference counting or some other cache logic would allow the Factory to prune unused stores.
How far off base am I with this approach? Is there a simpler approach that still scales?