3 ms·
> Annoying sure, but necessary right? No, not necessary. The key insight here is that the transitions are the hard part. One way to solve this is to write your
by rcme 4y ago
> Annoying sure, but necessary right?
No, not necessary. The key insight here is that the transitions are the hard part. One way to solve this is to write your transitions as a series of asynchronous steps that feed into each other. The end result is an asynchronous chain of operations.
E.g. if you have a video app, playing a video might look like:
1) Read the user metadata from disk.
2) Use the user metadata to make a network request for the video metadata.
3) Deserialize the video metadata on a background thread.
4) Present the video player with the video metadata on the main thread.
You compose each step into a chain of operations. Each step in the chain contains async work as well as logic that “cleans up” the work. So when you want to play a video, your code says “start the complicated video chain.” When you want to stop the video, your code says “stop the video chain.” The chains are a generic sequence of steps, so they can be stopped in the middle. Each step contains its own cleanup logic, so the cleanup of any pending work can happen automatically upon stopping the chain.
tldr: “state” the user is in at any given time is so complex that it’s impossible model with a state machine. It’s easier to think of cascading asynchronous steps instead. A good library for writing this kind of code is called Rx.
- joshka 4y agoIt's been a while since I wrote any Rx in earnest, but when I did, it was useful to look at it as almost exactly what you'd end up if you incorporated time (via ordered streams/publishers/observers/etc.) into a model that represents a state machine model. That is to say, you can kinda both be right here. ;)