3 ms·
Now being able to just dig into the lower level of Futures at work, I'd say even that is not that hard. You just write the `poll` function and then pattern matc
by pimeys 7y ago
Now being able to just dig into the lower level of Futures at work, I'd say even that is not that hard. You just write the `poll` function and then pattern match inside. There are even nice macros, such as the `ready!` that helps you with some of the boilerplate.
The trickiest thing for me to grasp first was the `Pin` type. Like how does this prevent the value to be moved... Until I realized it's `Pin<&mut T>` and then I had my a-ha moment.
- Arnavion 7y agoIt's slightly more complicated than just pattern-matching. - In general you have to be careful that if you're returning Poll::Pending, it's after something has registered a wakeup, otherwise your future is going to just stop. - As a specific case, your match has to be inside a loop so that a state transition results in the new state being polled immediately. You can't just return and expect the caller to poll() you since there will be no wakeup registered that triggers the caller to do so. - Because futures receive `&mut Self` rather than `Self`, it's difficult to do a state transition where the new state needs to own some properties of the current state. Eg `State::Foo { id: String } -> State::Bar { id: String }` Instead you have to do Option::take / std::mem::replace shenanigans on the state fields, or have an ugly State::Invalid that you can std::mem::replace the whole state with.