cwharris cwharris

Niner since 2013


  • Tip 3: Wrap events up in ​Task-​returning APIs and await them

    Actually, Lucian did a pretty good job writing the Rx implementation of this code, but I'll go back and rewrite both to show how to *use* them. BBL.

  • Tip 3: Wrap events up in ​Task-​returning APIs and await them

    I whole-heartily agree with @wekempf on the point of IObservable vs Task. Task has a one-off "I did this, here's the result" concept, and IOberservable has an "events over time" concept.

    The while(true){} is a code smell, and it indicates that there's missing code. Mainly, the ability to stop listening to the "event stream". If I wanted it to stop, I'd have to kill the thread it's running on.

    IObservable also gives us more composition options through the use of Reactive Extensions. Moreover, it's cross-language compatible, and doesn't use any compiler-specific features on an "API".

    Lets talk about the return types of the two functions illustrated. The async example's return type is void. Meaning that it isn't functional, and the entire call is definitely a side-effect. It also means if I wanted to re-use this shake-detection code in more than one place, I'd either be injecting a callback into the method (remember when you suggested we didn't have to use a lambda in the async version?), or I'd have to write two entirely separate methods with different side effects. Both of those are no-nos.

    The IObservable, on the other hand, simply composes the events in a functional manner without creating any side effects, and gives the consumer the ability to either compose the events further, or add multiple explicit, properly-placed side effects without injecting a lambda, or copying code.

    While the async stuff has it's uses, complex event handling is not one of them.

    Interesting, thought-provoking example. Thanks!