<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Lesh on Medium]]></title>
        <description><![CDATA[Stories by Ben Lesh on Medium]]></description>
        <link>https://medium.com/@benlesh?source=rss-da6839d28258------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VZq_2zYok1sdOdgysqdhDg.jpeg</url>
            <title>Stories by Ben Lesh on Medium</title>
            <link>https://medium.com/@benlesh?source=rss-da6839d28258------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:02:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benlesh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Observables are “just functions”, but also collections… How do I name them?]]></title>
            <link>https://benlesh.medium.com/observables-are-just-functions-but-also-collections-how-do-i-name-them-918c5ce2f64?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/918c5ce2f64</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 22:15:15 GMT</pubDate>
            <atom:updated>2018-06-07T22:24:36.500Z</atom:updated>
            <content:encoded><![CDATA[<p>Naming things is hard. Naming things in programming is even harder, IMO. <a href="https://github.com/reactivex/rxjs">RxJS</a> and observables bring more confusion for some people when it comes to naming because they’re just not sure what to make of them. Observables are a lazy type that, when subscribed to, pushes values at you like a collection. Observables can have side effects, just like functions. Observables might <em>just</em> have side effects, in fact.</p><p>In truth, it probably doesn’t matter too much how you name them, as long as you’re consistent, you can understand your code, and perhaps more importantly, your team and/or the person that comes after you can understand your code.</p><h3>Here are a few rules of thumb I follow:</h3><ol><li><strong>Pluralize observables that could give you many values.</strong> accounts$, videos$, cheeses$, etc.</li><li><strong>Singular nouns for observables that just give you one value. </strong>person$, account$, score$. Just be aware that the $ on the end (if you’re using <a href="https://medium.com/@benlesh/observables-and-finnish-notation-df8356ed1c9b">Finnish Notation</a>) might be confused as pluralization.</li><li><strong>Add a </strong><strong>maybe prefix in front of observables that might not give you a value at all. </strong>maybeData$, maybeBirds$, you get the idea. If the observable might complete before it gives you a value, put a maybe on it.</li><li><strong>If the observable is all about the side effect, name it like you might name a function.</strong> Give it a verb and noun combination that describes what it’s doing, and what it’s doing it to. performBounceAnimation$, addButtonElement$, updateAccountData$, and so on.</li><li><strong>If the content is ambiguous, name it by intent</strong>. For example, if you have an Observable&lt;number&gt; that is mean to be clock ticks, name it clockTicks$, not incrementingNumbers$, that’s just weird and isn’t going to help anyone that comes after you.</li><li><strong>Try not to confuse people. </strong>maybeUpdateAccountData$ is probably a no-no if you’re just being a pedant about the word <em>“maybe”</em>. Yes, we all know that your HTTP call might fail resulting in no values. Likewise, don’t name them all like functions because <em>“creating a log on the http server is technically a side-effect”</em>. Just relax. <strong>Naming observables is not a science.</strong></li></ol><h3>$ is OPTIONAL</h3><p><a href="https://medium.com/@benlesh/observables-and-finnish-notation-df8356ed1c9b">Finnish Notation</a> is all over the place, but in truth it doesn’t really matter. It might help your team in RxJS-heavy applications as it could avoid ambiguous variable names where you have a foos$ observable that you’re subscribing to and updating some other foos variable. If you do postfix with a $, do not include the $ like an “s” for pluralization. I know I’ve done that and advocated it in the past, but I’ve since found it’s confusing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918c5ce2f64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging TypeScript Mocha Tests With VSCode]]></title>
            <link>https://benlesh.medium.com/debugging-typescript-mocha-tests-with-vscode-89310051531?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/89310051531</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 19:31:25 GMT</pubDate>
            <atom:updated>2018-04-25T19:31:25.515Z</atom:updated>
            <content:encoded><![CDATA[<p>Visual Studio Code is a powerful IDE, and my editor of choice while working on RxJS. They have some amazing debugging features, but I was having a really hard time getting it to work with TypeScript-based Mocha tests while working on the experimental branch of RxJS.</p><p>The following is my configuration that got things working for Mocha and TypeScript debugging with VSCode:</p><p>(Note: You’ll want to change modules/**/*-spec.ts to a glob that matches your test files)</p><pre>{<br>  &quot;version&quot;: &quot;0.2.0&quot;,<br>  &quot;configurations&quot;: [<br>    {<br>      &quot;type&quot;: &quot;node&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;name&quot;: &quot;Mocha All&quot;,<br>      &quot;program&quot;: &quot;${workspaceFolder}/node_modules/mocha/bin/_mocha&quot;,<br>      &quot;args&quot;: [<br>          &quot;-r&quot;,<br>          &quot;ts-node/register&quot;,<br>          &quot;--timeout&quot;,<br>          &quot;999999&quot;,<br>          &quot;--colors&quot;,<br>          &quot;${workspaceFolder}/modules/**/*-spec.ts&quot;,<br>      ],<br>      &quot;console&quot;: &quot;integratedTerminal&quot;,<br>      &quot;internalConsoleOptions&quot;: &quot;neverOpen&quot;,<br>      &quot;protocol&quot;: &quot;inspector&quot;<br>  },<br>  ]<br>}</pre><h3>How I Got There</h3><p>RxJS experimental branch is using ts-node and mocha together to run our tests. The npm script for this looks like so:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;mocha -r ts-node/register modules/**/*-spec.ts&quot;<br>},</pre><p>If you’ll notice, almost the same as the &quot;program&quot; and &quot;args&quot; sections of the debugger config above. The main difference is we’re actually pointing directly to the mocha executable in ${workspaceFolder}/node_modules/mocha/bin/_mocha and then we have added a few additional arguments to do things like make colors display, and make sure that it doesn’t timeout the tests while we’re paused in the debugger.</p><h3>Dealing With “legacy protocol” Messages</h3><p>I still wasn’t exactly able to step into my code yet, and I noticed in the <strong>debug console</strong> that I had this message:</p><blockquote>Debugging with legacy protocol because Node.js v7.7.2 was detected.</blockquote><p>I have no idea what’s causing that, I’m using version 8 of node when I check in terminal… but it’s not important. In order to solve that, I had to add &quot;protocol&quot;: &quot;inspector&quot; to my configuration in <strong>launch.json</strong>. After that, I was able to step into code while debugging.</p><h3>That’s It!</h3><p>I hope this article helps someone else, or at the very least, I hope I remember I wrote it the next time I run into this issue. I just wanted to document it for the internet, seeing as I couldn’t find exactly what I needed to do in any one spot. Just bits and pieces.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89310051531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“But I Thought You Were Already On The Angular Team?”]]></title>
            <link>https://benlesh.medium.com/but-i-thought-you-were-already-on-the-angular-team-1ff1029bc308?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff1029bc308</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Wed, 21 Mar 2018 20:09:31 GMT</pubDate>
            <atom:updated>2018-03-21T20:09:31.839Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR: No. I wasn’t, but now I am. I’ll have more time to support RxJS. RxJS will remain an independent OSS project, and will not cater only to Angular, but will continue to serve all of our many partners throughout the JavaScript community.</strong></p><p>I’ve been working at Google for a little over a year now, and <em>many</em> people have thought that during this time I’ve been working on the Angular Team. Even <em>more </em>people have thought I worked on RxJS full time. Neither of those things were even close to true.</p><p>Over the past year I’ve been working on Alkali, which is an internal platform-as-a-service built with Angular and Java (and a host of other technologies including RxJS). It is a fantastic project, and an even better group of people, and I’m sad to be leaving them. Fortunately, they’re just downstairs, so I’m not <em>that</em> sad.</p><p>During this time, I’ve only been able to put in a few hours a week on RxJS, usually picking one night a week to stay late, forgoing seeing my family, and trying to get things done. It has been really hard to keep up with the demands of the repository during this time period, but we’ve managed.</p><p>Given that RxJS is Angular’s only dependency, and given that RxJS is very widely used at Google (even outside of Angular), it made sense that I move into a position where I can better support RxJS for Angular and the rest of Google. Angular, of course, has a lot of need for someone with reactive programming and RxJS experience.</p><h4>Will RxJS Still Support React? Ember? Vue? Node?</h4><p><strong><em>Of course!!!</em></strong> While supporting the Angular Team is my job, it’s also my job to make sure RxJS does what’s right for the RxJS community, and the Angular Team understands that and fully supports the goal of keeping RxJS a thriving, independent, open source community. If they didn’t support that, I would not have joined. Angular is indeed the biggest partner RxJS has, but that does not mean RxJS will forget about all of its other partners we happily support.</p><p>For my part, I still <em>love</em> React, and during my time at Netflix (my previous job) I have more time under my belt using React than anything else at this point. I also really enjoyed working on Ember apps at Netflix. It’s very important to me to continue to support these communities, and we have other RxJS Core Team members who use these technologies every day.</p><p>I hope I can bring my years of experience developing web applications with various technologies and frameworks to Angular to help make it even better, and even more reactive!</p><p>The Angular Team is a wonderful group of people who have provided a tremendous amount of support to me over the years, and I’m very much looking forward to returning the favor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff1029bc308" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS Observable interop with Promises and Async-Await]]></title>
            <link>https://benlesh.medium.com/rxjs-observable-interop-with-promises-and-async-await-bebb05306875?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebb05306875</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Wed, 23 Aug 2017 01:11:28 GMT</pubDate>
            <atom:updated>2017-08-23T01:21:30.624Z</atom:updated>
            <content:encoded><![CDATA[<p>Every now and then I’m asked a question about how to use async functions or promises with RxJS, or worse, I’m told some “fact” about how async-await and Observables don’t really “work together”. RxJS has, from inception, had a high degree of interoperability with Promises. Hopefully this article will shed some light on that.</p><h3>If it accepts Observable, it accepts Promise</h3><p>For example, if you’re using a switchMap, you can return a Promise inside of there just the same as you can return an Observable. All of these are valid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1ff06124ef46c099a82bf75e32a34f7/href">https://medium.com/media/c1ff06124ef46c099a82bf75e32a34f7/href</a></iframe><h3>Make a Promise-returning function retryable with defer</h3><p>If you have access to the function that creates the promise, you can wrap it with Observable.defer() and make an Observable that can be retried on error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26d4f756977366358c58a212b1107d1d/href">https://medium.com/media/26d4f756977366358c58a212b1107d1d/href</a></iframe><h3>Define an Observable with async-await using defer()</h3><p>Defer is a very powerful little tool, it turns out. You can use it, basically directly, with async functions and it will make an Observable that emits the returned value and completes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2242ec4841d3a8d136864ed6663afa39/href">https://medium.com/media/2242ec4841d3a8d136864ed6663afa39/href</a></iframe><h3>Subscribe to an Observable with forEach to create concurrent tasks in async-await</h3><p>This is a lesser-used feature of RxJS that comes from the TC39 Observable proposal. There is more than one way to subscribe to an Observable! There’s subscribe, which is the classic way to subscribe to an Observable, and it returns a Subscription object which can be used for cancelling the data stream… and there’s forEach which is a non-cancellable way of subscribing to an Observable that takes one function for each next-ed value, and returns a Promise that embodies the completion and error paths for the Observable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c490b4dca617998c2eb0667b1e12f6bc/href">https://medium.com/media/c490b4dca617998c2eb0667b1e12f6bc/href</a></iframe><h3>Use toPromise() with async/await to emit the last Observable value as a Promise</h3><p>The toPromise function is actually a bit tricky, as it’s not really an “operator”, rather it’s an RxJS-specific means of subscribing to an Observable and wrap it in a promise. The promise will resolve to the last emitted value of the Observable once the Observable completes. That means that if the Observable emits the value “hi” then waits 10 seconds before it completes, the returned promise will wait 10 seconds before resolving “hi”. If the Observable <em>never</em> completes, then the Promise never resolves.</p><p><strong>NOTE: using toPromise() is an <em>antipattern</em> except in cases where you’re dealing with an API that expects a Promise, such as async-await</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfbf2a8bd47fe4c115c2bb34ccab2590/href">https://medium.com/media/dfbf2a8bd47fe4c115c2bb34ccab2590/href</a></iframe><h3>Observables and Promises work well together</h3><p>Admittedly, if you’re aiming for reactive programming, <em>most</em> of the time, you probably want an Observable, but RxJS tries to be as ergonomic as possible in a world where Promises are so popular. Furthermore, using RxJS Observables with forEach in async functions enables a lot of interesting possibilities for managing concurrency and tasks in a way that “just works” with async-await.</p><p><strong>Come learn more about RxJS from me in-person or online at </strong><a href="http://rxworkshop.com"><strong>http://rxworkshop.com</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebb05306875" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise Cancellation Is Dead — Long Live Promise Cancellation!]]></title>
            <link>https://benlesh.medium.com/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6601f1f5082</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Sat, 31 Dec 2016 00:59:35 GMT</pubDate>
            <atom:updated>2017-09-04T16:42:21.943Z</atom:updated>
            <content:encoded><![CDATA[<p>Not very long ago <a href="https://twitter.com/domenic">Domenic Denicola</a> (worth a follow, a very smart guy) withdrew <a href="https://github.com/tc39/proposal-cancelable-promises">his proposal for promise cancellation from the TC39</a>. A lot of people might think that means that promise cancellation isn’t coming to JavaScript. Those people would be right, if you couldn’t already cancel a promise via very similar means to what was proposed.</p><p>I want to be clear: <strong>You can’t cancel a Promise</strong>. (I know, I know, mixed messages)… If something gives you a promise, your ability to cancel it has already been decided for you… you can’t. This is because promises, unlike Observables, are eager. Once you have a promise, the process that will produce that promise’s resolution is already underway, and you generally don’t have access to prevent that promise’s resolution any more. More importantly you can’t tear down resources. You must opt into cancellation the moment that the Promise is created.</p><p>So what can you do? Well, here are four options (there are more)… but you can jump to the end to find out how Promise Cancellation might have affected Rx and Observables.</p><h4>Option 1 - Use Bluebird</h4><p>Okay, “You can’t cancel a promise, unless it’s from Bluebird”. 😁</p><p><a href="http://bluebirdjs.com">Bluebird</a> has it’s own <a href="http://bluebirdjs.com/docs/api/cancellation.html">API for promise cancellation</a>. It will give you an onCancel callback that you can use to register logic to tear down your data producer, and it also tacks a cancel method on the promise itself you can use to cancel that promise.</p><pre>// Bluebird promise cancellation<br>const promise = new Promise((resolve, reject, onCancel) =&gt; {<br>  const id = setTimeout(resolve, 1000);<br>  onCancel(() =&gt; clearTimeout(id));<br>});</pre><pre>// use the promise as usual<br>promise.then(() =&gt; console.log(&#39;done&#39;));</pre><pre>// anytime later<br>promise.cancel();</pre><p>It’s a solid and concise API that I think is simple for users to grok. The only thing I’m not sure about with it is that fact that the cancellation semantic isn’t cleanly separated from the promise.</p><h4>Option 2 - Use Another Promise</h4><p>The TC39 proposal was using a CancelToken. CancelToken by any other name was really just a Promise with a properly on it called reason that you could use to synchronously check to see if you’d already been cancelled. This is something Bluebird’s approach lacks, AFAICT, but that’s not really that big of a deal, because technically, so does this approach</p><p>Either way, if you want to have a CancelToken, and you’re sad you don’t have one, you can just use another Promise. In the code below, createToken is to make up for the lack of CancelToken.source method to create a cancel token and it’s paired cancel function.</p><pre>// a basic stitched-together CancelToken<br>// creation mechanism<br>function createToken() {<br>  const token = {};<br>   token.promise = new Promise(resolve =&gt; {<br>    cancel = (reason) =&gt; {<br>      // the reason property can be checked<br>      // synchronously to see if you&#39;re cancelled<br>      token.reason = reason;<br>      resolve(reason);<br>    });<br>  };<br>  return { token, cancel };<br>}</pre><pre>// create a token and a function to use later.<br>const { token, cancel } = createToken();</pre><pre>// your functions that return promises would also take<br>// a cancel token<br>function delay(ms, token) {<br>  return new Promise(resolve =&gt; {<br>    const id = setTimeout(resolve, ms);<br>    token.promise.then((reason) =&gt; clearTimeout(id));<br>  });<br>};</pre><p>The above is a hacky example, to be sure, and it doesn’t include other features the proposal would add to the language (a try/catch/else semantic, for example, where cancellation would actually throw a special cancel error).</p><h4>Option 3 - Use Rx Subscriptions</h4><p>If you’re already using RxJS, and really, really just want a promise (I’m not sure why you would if you already have Rx, but that’s not the point). You can use Rx.Subscription to cancel a token:</p><pre>// create a subscription to use with your promise<br>const subscription = new Rx.Subscription();</pre><pre>const promise = new Promise(resolve =&gt; {<br>  const id = setTimeout(resolve, 1000);<br>  // add teardown logic to the subscription<br>  subscription.add(() =&gt; clearTimeout(id));<br>});</pre><pre>// use the promise as usual<br>promise.then(() =&gt; console.log(&#39;done&#39;));</pre><pre>// call unsubscribe at any point to cancel<br>subcscription.unsubscribe();</pre><h4>Option 4 - Ditch promises and just use Observables! (This author’s totally biased choice)</h4><p>Okay, this isn’t an answer, but if you’re already using Observables, you could just use an observable, it’s not that much different from a promise, other than it’s lazy, it’s built to handle more than one value if needed, and it’s cancellable.</p><pre>// create an observable, you can return teardown logic<br>const source$ = new Rx.Observable(observer =&gt; {<br>  const id = setTimeout(() =&gt; observer.next(), 1000);<br>  return () =&gt; clearTimeout(id);<br>};</pre><pre>// subscribing gives you a subscription<br>const sub = source$.subscribe(() =&gt; console.log(&#39;done&#39;));</pre><pre>// cancel at any time later<br>sub.unsubscribe();</pre><p>Just be aware that promises and observables have some semantic differences. Observables don’t multicast by default and aren’t always asynchronous. You can model a promise with an observable, but not the other way around. This is because observables are a little lower-level than a promise. <a href="https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87">Observables are really just functions that take observers</a>, after all.</p><h4>How Promise Cancellation Would Have Effected Observables</h4><p>I personally liked the CancelToken approach, because it would have given JavaScript a known, ubiquitous cancellation type that we could have leveraged in RxJS. As an author of an Observable type, I can tell you that CancelToken made <em>my</em> job much easier, and probably would have reduced the size of the RxJS code base substantially. However, in a world where CancelToken isn’t being used with every promise, async/await function, etc, users already having access to a pre-made token would become rare, and ergonomics would suffer if we moved to a token-based model.</p><pre>// current Observables<br>const subscription = someObservable$.subscribe(observer);<br>subscription.unsubscribe();</pre><pre>// with CancelToken<br>const { token, cancel } = CancelToken.source();<br>someObservable$.subscribe(observer, token);<br>cancel();</pre><p>In the end though, if you want cancellation, you’re probably better off with Observables. They’ve been designed for cancellation from the beginning, and they’re designed to be compatible with more different types of data producers and async sources. Observables can represent animations, user interactions (clicks, mouse moves, etc), ajax, web sockets, arrays, iterables and many, many more things. Promises are great, but you’re going to see a lot more of the benefits of same-kindedness and composition if you’re using observables than you will if you’re using Promises. But that’s probably a different post for a different time.</p><blockquote>A little about me: I am the lead author of RxJS 5 and I run workshops on async programming and RxJS at <a href="http://rxworkshop.com">RxWorkshop.com</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6601f1f5082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On The Subject Of Subjects (in RxJS)]]></title>
            <link>https://benlesh.medium.com/on-the-subject-of-subjects-in-rxjs-2b08b7198b93?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b08b7198b93</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[observables]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Sat, 10 Dec 2016 07:08:10 GMT</pubDate>
            <atom:updated>2017-09-12T17:08:09.662Z</atom:updated>
            <content:encoded><![CDATA[<p>Subjects in RxJS are often misunderstood. Because they allow you to imperatively push values into an observable stream, people tend to abuse Subjects when they’re not quite sure how to make an Observable out of something. The pattern looks a little like this…</p><pre>// What people usually first do with Subjects when they find them<br>// (TRY NOT TO DO THIS)</pre><pre>const subject = new Subject();<br>button.addEventListener(‘click’, () =&gt; subject.next(&#39;click&#39;);<br>subject.subscribe(x =&gt; console.log(x));</pre><p>While this is helpful for people new to RxJS (and in that capacity <em>totally</em> fine), it’s not really the “Rx way” to handle things like this. Ideally you’d wrap your event registration in an Observable that can set it up and tear it down. Which looks more like this:</p><pre>// This is better, but use Observable.fromEvent(button, &#39;click&#39;)<br>// instead, please.</pre><pre>const clicks = new Observable(observer =&gt; {<br>  const handler = (e) =&gt; observer.next(e);<br>  button.addEventListener(&#39;click&#39;, handler);<br>  return () =&gt; button.removeEventListener(&#39;click&#39;, handler);<br>});</pre><p>Why show this when it has nothing to do with Subjects? Well, for one thing, it shows why you don’t always need to use a Subject, and for another thing, there’s a subject hidden in here… sort of. The thing to note here, is that the Observable is wrapping the registering of the handler on the button via addEventListener, which itself is a subject. …at least per the “<a href="https://en.wikipedia.org/wiki/Design_Patterns">Gang Of Four</a>” <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer Pattern</a>.</p><h4>The Observer Pattern</h4><p>As you may know, RxJS is mostly about Observables and Observers… but it’s also about Subjects. While observables aren’t something you’ll find in the GoF’s <a href="https://en.wikipedia.org/wiki/Design_Patterns">Design Patterns</a>, Subjects and Observers are the meat-and-potatoes of the <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer Pattern</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*isWKTKNBoQrE5av1FZr6wQ.png" /><figcaption>(Source: Wikipedia)</figcaption></figure><p>The pattern is pretty straight forward. Observers are a class with a notification method on it, and Subject is a class with a means to add or remove an observer to/from a list of internal observers, and a method to notify that list of observers.</p><p>Subjects in RxJS aren’t much different. When you call subscribe with an observer on an Rx Subject, it will add that observer to an internal list of observers. Likewise, if you call subscribe with one to three functions, it wraps them in an observer, and adds it to its list of observers. When you call next(value) on the Subject, it will loop through its list of observers and forward that value along to their next methods. It does the same thing for error and complete. To remove your observer from the subject’s list of observers, you simply call unsubscribe on the subscription returned when you added the observer to the list.</p><pre>const subject = new Subject();</pre><pre>// add observer1 to the list of observers<br>const sub1 = subject.subscribe(observer1);</pre><pre>// add observer2 to the list of observers<br>const sub2 = subject.subscribe(observer2);</pre><pre>// notify all observers in the list with &quot;hi there&quot;<br>subject.next(&#39;hi there&#39;);</pre><pre>// remove observer1 from the list<br>sub1.unsubscribe();</pre><h4>Subject Compared To Observable</h4><p>Effectively, RxJS Subjects different take on the GoF Observer Pattern Subjects, but their API duck-types as an Observable. In fact, in RxJS, Subjects even inherit from Observable. The advantage here is that all Subjects then have the same operators and methods available to them as Observables do.</p><p>Probably a more important distinction between Subject and Observable is that a Subject has state, it keeps a list of observers. On the other hand, an <a href="https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87">Observable is really just a function</a> that sets up observation.</p><p>While Subjects are Observables, Subjects also implement an Observer interface. That is to say, they have next, error, and complete methods. These methods are used to notify their counterparts on observers in the subject’s internal observers list. This means a subject can be used as an observer to subscribe to any observable.</p><pre>// To &quot;share&quot; the observable tick$ with two observers,<br>// observer1 and observer2, we can pipe all notifications<br>// through a Subject, like so</pre><pre>const tick$ = Observable.interval(1000);<br>const subject = new Subject();</pre><pre>subject.subscribe(observer1);<br>subject.subscribe(observer2);</pre><pre>tick$.subscribe(subject);</pre><p>The example above is “multicasting” the observable tick$ to two observers: observer1 and observer2. This is actually what almost all multicasting operators in RxJS do internally. For example publish, publishReplay, multicast, share, etc. Really, this is the primary use case for Subjects in RxJS.</p><h4>Subjects Are Not Reusable</h4><p>In RxJS, Subjects cannot be reused. That is to say, when a Subject completes or errors, it can no longer be used. If you try to next on a Subject that is closed due to it’s complete or error method being called, it will silently ignore the notification. If you want the Subject to loudly and angrily error when you next to it after it’s done being useful, you can call unsubscribe directly on the subject instance itself.</p><pre>// The death of a Subject<br>const subject = new Subject();</pre><pre>subject.subscribe(x =&gt; console.log(x));</pre><pre>subject.next(1);    // 1<br>subject.next(2);    // 2<br>subject.complete();<br>subject.next(3);    // silently ignored</pre><pre>subject.unsubscribe();<br>subject.next(4);    // Unhandled ObjectUnsubscribedError</pre><h4>Gotchas in RxJS</h4><p>But it comes with some confusing pain points in current versions of RxJS. Since Rx observables do not “trap” errors, we can run into some strange behavior here. Error “trapping” is a behavior I myself have derided Promises for implementing, but in multicast scenarios it may be the right move. What I mean when I say Rx observable does not “trap” errors is basically that when an error percolates to the end of the observer chain, if the error is unhandled, it will be re-thrown.</p><pre>// Demonstrating re-throwing for lack of an error handler</pre><pre>const badObservable = Observable.throw(new Error(&#39;haha&#39;));</pre><pre>try {<br>  badObservable.subscribe({<br>    next: x =&gt; console.log(x),<br>    error: null,<br>    complete: () =&gt; console.log(&#39;done&#39;)<br>  });<br>} catch (err) {<br>  console.error(err); // logs our Error: &quot;haha&quot;<br>}</pre><p>Now let’s think of that behavior in terms of what happens when you’re looping over a list of observers and notifying them (as subject does)</p><pre>for (let observer of observers) {<br>  observer.next(&#39;notify&#39;); // What happens if this call throws??<br>}</pre><pre>// HINT: It&#39;s going to error and break the loop<br>// NOTE: Okay, that was more than a HINT.</pre><p>Given that a number of operators are processed synchronously, (map, filter, scan et al), if you have an error thrown in one of those, or any other synchronous operation, downstream from a multicast (which is using a Subject to loop over a list of observers and notify them), you can get some spooky behavior:</p><pre>// This is going to behave strangely</pre><pre>const source$ = Observable.interval(1000).share();</pre><pre>const mapped$ = source$.map(x =&gt; {<br>  if (x === 1) {<br>    throw new Error(&#39;oops&#39;);<br>  }<br>  return x;<br>});</pre><pre>source$.subscribe(x =&gt; console.log(&#39;A&#39;, x));<br>mapped$.subscribe(x =&gt; console.log(&#39;B&#39;, x));<br>source$.subscribe(x =&gt; console.log(&#39;C&#39;, x));</pre><pre>// &quot;A&quot; 0<br>// &quot;B&quot; 0<br>// &quot;C&quot; 0<br>// &quot;A&quot; 1<br>// Uncaught Error: &quot;oops&quot;</pre><p>In the example above, most users would expect A’s and C’s to keep notifying. It’s understandable that the second B’s observable dies, it had an error, but it’s rather confusing that the other streams and the source stream die. It shouldn’t be the case that an arbitrary third party can kill your shared observable stream and therefor unknown numbers of sibling streams. This is a leaky abstraction, and we need to fix it in upcoming versions of RxJS.</p><p>Working around the above scenario in the interim is easy thanks to schedulers. You can use observeOn after your multicast and you’ll get around this problem because errors will no longer be thrown synchronously.</p><pre>const source$ = Observable.interval(1000)<br>  .share()<br>  .observeOn(Rx.Scheduler.asap); // magic here</pre><pre>const mapped$ = source$.map(x =&gt; {<br>  if (x === 1) {<br>    throw new Error(&#39;oops&#39;);<br>  }<br>  return x;<br>});</pre><pre>source$.subscribe(x =&gt; console.log(&#39;A&#39;, x));<br>mapped$.subscribe(x =&gt; console.log(&#39;B&#39;, x));<br>source$.subscribe(x =&gt; console.log(&#39;C&#39;, x));</pre><pre>// &quot;A&quot; 0<br>// &quot;B&quot; 0<br>// &quot;C&quot; 0<br>// &quot;A&quot; 1<br>// Uncaught Error: &quot;oops&quot;<br>// &quot;C&quot; 1<br>// &quot;A&quot; 2<br>// &quot;C&quot; 2 <br>// &quot;A&quot; 3<br>// &quot;C&quot; 3<br>// ... etc</pre><p>Another workaround, that’s a little more performant if you can manage it, is to simply add an error handler to all of your subscriptions.</p><pre>const source$ = Observable.interval(1000)<br>  .share()<br>  .observeOn(Rx.Scheduler.asap); // magic here</pre><pre>const mapped$ = source$.map(x =&gt; {<br>  if (x === 1) {<br>    throw new Error(&#39;oops&#39;);<br>  }<br>  return x;<br>});</pre><pre>source$.subscribe(x =&gt; console.log(&#39;A&#39;, x));<br>mapped$.subscribe(<br>  x =&gt; console.log(&#39;B&#39;, x),<br>  err =&gt; console.log(&#39;Error handled: &#39; + err.message)<br>);<br>source$.subscribe(x =&gt; console.log(&#39;C&#39;, x));</pre><pre>// &quot;A&quot; 0<br>// &quot;B&quot; 0<br>// &quot;C&quot; 0<br>// &quot;A&quot; 1<br>// &quot;Error handled: oops&quot;<br>// &quot;C&quot; 1<br>// &quot;A&quot; 2<br>// &quot;C&quot; 2 <br>// &quot;A&quot; 3<br>// &quot;C&quot; 3<br>// ... etc</pre><h4>The Future Of Observable</h4><p>The newer incarnation of the <a href="https://github.com/tc39/proposal-observable">TC39 Observable proposal</a>, not including the CancelToken business, which is an entire article by itself, is likely going to get around this behavior by “trapping” the error if there is no error handler. That is to say, it’s not going to re-throw errors that make it to the end of the observer chain. In future versions of RxJS I think we’re going to do the same thing, because it’s the right thing to do. The issue is open for debate, of course, but it’s unlikely to meet much resistance in my opinion.</p><h4>Summary</h4><ol><li>Subjects are both observer and observable</li><li>Subjects “multicast” to an internal list of observers</li><li><a href="https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87">Observables are just functions</a> that set up observation</li><li>Observables currently don’t trap errors but they should</li><li>Errors thrown synchronously downstream from a Subject can kill the Subject</li><li>You can use an error handler or observeOn to fix the problem in #4</li><li>I was wrong about Promise error trapping. It’s a good idea, because promises are multicast.*</li><li>Future versions of RxJS are likely to trap errors.</li></ol><ul><li>Although maybe not totally necessary, as promises are always async. (shrug)</li></ul><blockquote>A little about me: I am the lead author of RxJS 5 and I run workshops on reactive programming with RxJS at <a href="http://rxworkshop.com">RxWorkshop.com</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b08b7198b93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts On Mentorship In Tech]]></title>
            <link>https://benlesh.medium.com/thoughts-on-mentorship-in-tech-d46c8401c23c?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/d46c8401c23c</guid>
            <category><![CDATA[mentorship]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Tue, 02 Aug 2016 02:25:40 GMT</pubDate>
            <atom:updated>2016-08-02T02:28:05.346Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last 4–5 years I’ve had the amazing opportunity to mentor some even more amazing people. I want to share what I’ve learned.</p><h4>Mentoring comes in all shapes and sizes</h4><p>You might be mentoring someone right now and not realize it! Do people ask your opinion? Do you get hit up for advice? Congratulations, you’re probably mentoring!</p><p>Everyone has things they know and things they don’t. This means there’s always an opportunity to learn from or teach someone else. In tech especially, everyone is a beginner at something. Sometimes the best mentorship match up is between two people close to each other’s skill level, they might be able to relate to one another a little better.</p><p>There’s also no real timetable on mentorship. It doesn’t need to be a long-term relationship. It could just be a single pairing session, or perhaps it lasts a good portion of your career, who knows?</p><p>The only thing that’s important here is that both parties grow because of the relationship. Not only should the understudy grow and learn, but the mentor should as well.</p><h4>Where do I find someone to mentor?</h4><p>There are a lot of ways to do this. You could volunteer at a program to teach kids, or help at a workshop for people under-represented in tech. Or just help at any old workshop.</p><p>Personally, when I see someone working on a technology I’m really familiar with, and they’re a little new or they’re struggling, I just offer to pair with them. It’s simple to just ask, it just takes a little bravery on your part. Pairing can be done over the internet with tools like Screenhero or even Google Hangouts.</p><h4>Remember: Mentorship is scary for everyone</h4><p>The first thing to remember is that mentorship is scary for those being mentored. Odds are, this person admires your skill in some way and looks up to you. They probably feel vulnerable because they’re asking for your help, or worse they were told they needed mentoring. More than likely, this person is scared you will judge them harshly or reject them in some way. Worse, doing so, even via misunderstanding, could turn them off from their work entirely.</p><p>The next thing to remember is that mentorship is scary for mentors too. Mentors have a huge responsibility to those they’re teaching. You’re shaping their future and you owe them your best.</p><blockquote>Note for the mentored: Your mentor might be really nervous to mess up in front of you, too! This person is supposed to be an “expert” and maybe they don’t feel like they are. If they mess up in front of you, they’ll lose their credibility.</blockquote><h4>Don’t help too much</h4><p>You need to make sure that the person you’re mentoring is learning. This person is smart. Everyone is. We’re all the same species of ape that figured out how to build cities, fly and land ourselves on the moon… They’ll get it eventually.</p><h3>Ben Lesh on Twitter</h3><p>When you know the person you mentor is really smart, sometimes just wait a little bit... w/ @ladyleet on @screenheropic.twitter.com/n9NU2Uoudg</p><p>Teaching requires that you be willing to step back and allowing learning to happen.</p><ol><li>Give them the basic knowledge and idea and show them an example. Maybe walk through the first time they apply this new technique or skill.</li><li>After that, do not help until they REALLY need it. They might ask you for help very quickly, but give them a while to try to figure it out on their own.</li><li>If they can’t figure it out on their own, tell them where to look, give them a hint, and stand back.</li><li>If #3 fails, gently and patiently go back to #1 and work with them.</li></ol><h4>Patience and empathy</h4><p>Neither one of you was born knowing whatever you’re teaching them. At some point, you were just as beginner as them, and all of us have felt vulnerable. Try not to get frustrated. Remember not everything has been easy for you, either. We can all remember a point where we had a hard time grasping something.</p><h4>Point out when you learn something from your understudy</h4><p>While mentoring someone, I can guarantee they’ll do something you’ve never seen before. Maybe it’s a shell command you’ve never used. Maybe you learn something from them that’s unrelated to code: A new word, some fact about music, how to fold origami chopstick holders.</p><p><strong>Let them know you’ve learned from them!</strong> In my opinion, you should let everyone know what you’ve learned from them if you can. Show the person you’re mentoring they have something to offer you and that you’re still learning.</p><h4>Celebrate their victories!</h4><p>Whenever the person you’re mentoring finishes a tough assignment, or figures out a problem on their own, be generous with praise. It’s so important to let them know that you take personal pride in their victories.</p><p><strong>Remember: You don’t own their achievements! </strong>They have done the hard work. You were only there to guide them.</p><blockquote>Note to the mentored: Be sure to provide your mentors with a little praise for victories you feel you can attribute to their mentorship. Encouragement is something everyone loves at any level of their career.</blockquote><h4>Protect and guide them</h4><p>Remember that the internet, and in particular open source, can be a harsh battleground for newbies to enter. If someone is just starting out, it can be really disheartening to get derided by a grumpy troll on GitHub.</p><p>Protect those you mentor if you can see they’re struggling with a harsh critic. Talk to them about a time the same thing happened to you. Remind them of how far they’ve come and assure them that someday they’ll be “the expert”, and they can make better decisions about how to treat people than the troll they’ve encountered.</p><p>Guide them through technical debates and open source politics. Remember there’s a learning curve there too.</p><blockquote>Important note: If you think the person you’re mentoring is being harassed, be sure to report the incident to whomever is appropriate as soon as possible. Most communities have a code of conduct (if yours doesn’t, it should!), and their leadership should be keen to enforce it.</blockquote><h4>NEVER, EVER pretend to know something you don’t</h4><p>This is a good rule to just follow in life in general, but I feel it particularly applies to mentorship.</p><p>It’s much better to tell the person you’re helping that you don’t know something than it is to teach them the wrong thing. Teaching them the wrong thing could send them down the wrong path later, or perhaps make them look foolish in public or at work. It’s really irresponsible to just make things up.</p><h4>MOST IMPORTANTLY: Have fun!</h4><p>This is paramount. Learning new things should be exciting and fun. Be sure to joke a little, provide rewards of some sort, bring snacks, etc. Learning is always easier when you enjoy it, and so is teaching.</p><blockquote>This post was inspired by my dear friend <a href="https://medium.com/u/97e183b9e5ec">Tracy Lee | ladyleet</a>, whom I’ve had the fun of pairing with and mentoring on various projects over the last few months.</blockquote><blockquote>Also a shout out to all those people who’ve mentored me over the years, you know who you are and there’s too many of you to list. I’m still being mentored by people that might not realize it. I would not have made it to where I am without you, nor would I continue to succeed.</blockquote><p>For additional reading on this from a different perspective, checkout <a href="https://medium.com/@raquelxmoss/creating-a-welcoming-space-for-beginners-522d9fc2ff5e">Creating A Welcoming Workspace For Beginners</a> by <a href="https://medium.com/u/60f252b1d71">Raquel Moss</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d46c8401c23c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS: Don’t Unsubscribe]]></title>
            <link>https://benlesh.medium.com/rxjs-dont-unsubscribe-6753ed4fda87?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/6753ed4fda87</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Wed, 27 Jul 2016 18:52:39 GMT</pubDate>
            <atom:updated>2017-10-10T19:52:48.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Well… okay, just don’t unsubscribe quite so much.</p><p>I’m often enlisted to help someone debug an issue with their RxJS code or figure out how to structure an app that is composing a lot of async with RxJS. When doing so, I generally see the same thing pop up over and over again, people keeping handles to tons and tons of subscription objects. Developers will invariably make 3 HTTP requests with an Observable, and then keep 3 subscription objects that they’re going to call when some event occurs.</p><p>I can see how it would happen. People are used to using `addEventListener` N times, and then having some clean up where they have to call `removeEventListener` N times. It feels natural to do the same with subscription objects, and for the most part you’re right. But there are better ways. Keeping too many subscription objects around is a sign you’re managing your subscriptions imperatively, and not taking advantage of the power of Rx.</p><h4>What imperative subscription management looks like</h4><p>Take for example this make-believe component (I’ll purposely make this non-React and non-Angular and somewhat generic):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4547368e34611a47ac1ff5b638de58c/href">https://medium.com/media/e4547368e34611a47ac1ff5b638de58c/href</a></iframe><p>In the example above, you can see I’m manually calling `unsubscribe` on three subscription objects I’m managing myself in the `onUnmount()` method. I’m also calling `this.dataSub.unsubscribe()` when someone clicks the cancel button on line #15, and again on line #22 when the user sets the range selector above 500, which is some threshold at which I want to stop the data stream. (I don’t know why, it’s a weird component)</p><p>The ugliness here is I’m imperatively managing unsubscriptions in multiple places in this fairly trivial example.</p><p>The only real advantage to using this approach would be performance. Since you’re using fewer abstractions to get the job done, it’s likely to perform a little better. This is unlikely to have a noticeable effect in the majority of web applications however, and I don’t think it’s worth worrying about.</p><p>Alternatively, you can always combine subscriptions into a single subscription by creating a parent subscription and adding all of the others like children. But at the end of the day, you’re still doing the same thing, and you’re probably missing out.</p><h4>Compose your subscription management with takeUntil</h4><p>Now let’s do the same basic example, only we’ll use the `takeUntil` operator from RxJS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5800aa60287f546f83650ef5313f2a38/href">https://medium.com/media/5800aa60287f546f83650ef5313f2a38/href</a></iframe><p>The first thing you might notice is it’s less code. That’s just one benefit. Another thing that’s happened here is I have composed a stream of `stop$` events that kill the data stream. That means when I decide I want to add another condition to kill the data stream, like say a timer, I can simply merge a new observable into `stop$`. Another thing that is readily apparent is I only have one subscription object that I’m managing imperatively. There’s no way around this, because this is where your functional programming is meeting your object-oriented world. JavaScript is an imperative language after all, and we have to meet the rest of the world half way at some point.</p><p>Another advantage to this approach is it actually <em>completes</em> the observable. That means there’s a completion event that can be handled anytime you want to kill your observable. If you just call `unsubscribe` on a returned subscription object, there’s no way you’ll be notified that the unsubscription happened. However if you use `takeUntil` (or others listed below), you will be notified the observable has stopped via your completion handler.</p><p>The last advantage I’ll point out is the fact that you’re actually “wiring everything up” by calling `subscribe` in <em>one place, </em>this is advantageous because with discipline it becomes much, much easier to locate where you’re starting your subscriptions in your code. Remember, observables don’t do anything until you subscribe to them, so the point of subscription is an important piece of code.</p><p>There is one disadvantage here in terms of RxJS semantics, but it’s barely worth worrying about in the face of the other advantages. The semantic disadvantage is that completing an observable is a sign that the producer wants to tell the consumer it’s done, where unsubscribing is the consumer telling the producer it no longer cares about the data.</p><p>There will also be a very slight performance difference between this and just calling `unsubscribe` imperatively. However, it’s unlikely that the perf hit will be anything noticeable in the mass-majority of applications.</p><h4>Other operators</h4><p>There are many other ways to kill a stream in a more “Rx-y” way. I’d recommend checking out the following operators at the very least:</p><ul><li>take(n): emits N values before stopping the observable.</li><li>takeWhile(predicate): tests the emitted values against a predicate, if it returns `false`, it will complete.</li><li>first(): emits the first value and completes.</li><li>first(predicate): checks each value against a predicate function, if it returns `true`, the emits that value and completes.</li></ul><h4>Summary: Use takeUntil, takeWhile, et al.</h4><p>You should probably be using operators like `takeUntil` to manage your RxJS subscriptions. As a rule of thumb, if you see two or more subscriptions being managed in a single component, you should wonder if you could be composing those better.</p><ul><li>more composeable</li><li>fires a completion event when you kill your stream</li><li>generally less code</li><li>less to manage</li><li>fewer actual points of subscription (because fewer calls to `subscribe`)</li></ul><p>Want to learn more about RxJS from me? Checkout <a href="http://rxworkshop.com">rxworkshop.com</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6753ed4fda87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observables and Finnish Notation]]></title>
            <link>https://benlesh.medium.com/observables-and-finnish-notation-df8356ed1c9b?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8356ed1c9b</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[finland]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Wed, 29 Jun 2016 16:55:13 GMT</pubDate>
            <atom:updated>2018-01-29T22:11:38.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPfggxiLsdLlsx1VRp23NQ.jpeg" /></figure><p>Once in a while I’m asked what I think about naming observables with an $ suffix. For example:</p><pre>const click$ = Observable.fromEvent(button, &#39;click&#39;);</pre><p>Well, I <em>personally </em>could take it or leave it, but I know some of you can’t live without it. What I want to write an article about, however, is the origin of “Finnish Notation” and different dialects.</p><h4>Hungarian Notation</h4><p>With <a href="https://en.wikipedia.org/wiki/Hungarian_notation">Hungarian Notation</a>, one adds a prefix to their variable names that denotes the type the variable contains. Generally, this prefix is about one to three characters in length. For example:</p><pre>const sTest = &quot;test&quot;;<br>const nShortPI = 3.14;<br>const obsClicks = Observable.fromEvent(domButton, &#39;clicks&#39;);</pre><p>Pros:</p><ul><li>In an untyped language like JavaScript, it becomes clearer what type might be in your variable.</li></ul><p>Cons:</p><ul><li>In an untyped language like JavaScript, sometimes variables like arguments to functions take more than one type, then what do you do?</li><li>It’s a lot more typing for minimal benefit.</li><li>May hurt readability in some cases?</li><li>With the advent of TypeScript and modern IDEs, Hungarian Notation isn’t really necessary in most languages, because the IDE gives you a lot of information about the variable while you’re working.</li></ul><h4>Non-Finnish Notation (ordinary variable names)</h4><p>As a rule, I generally don’t use either Hungarian notation or Finnish notation with my code. Here’s what that looks like:</p><pre>const test = &quot;test&quot;;<br>const shortPI = 3.14;<br>const clicks = Observable.fromEvent(button, &#39;click&#39;);</pre><p>Pros:</p><ul><li>Generally easy on the eyes. Not a lot of special character clutter or non-words. Just words you can read that ideally signify the intent of the variable.</li><li>Easy to use in situations where a variable may store more than one type at any given time. This happens a lot in JavaScript code, whether it’s good practice or not.</li></ul><h4>Finnish Notation</h4><h3>Ben Lesh on Twitter</h3><p>@andrestaltz @schwarty @_jayphelps Finnish Notation. Put it in Wikipedia. It was born today</p><p>This is a naming paradigm that I’ll attribute to <a href="https://twitter.com/andrestaltz">Andre Staltz</a>. Who is Finnish… Therefor, “Finnish notation”. The idea here is that you pluralize all variable names that contain <em>observables. </em>Like so:</p><pre>const test = &quot;test&quot;;<br>const shortPI = 3.14;<br>const click$ = Observable.fromEvent(button, &#39;click&#39;);</pre><p>Pros:</p><ul><li>Observables are REALLY easy to spot now. Before you might have just looked for a `subscribe` call or something.</li><li>Might be ideal for codebases where observable use is prolific. Things like Cycle.js or Angular 2 applications.</li></ul><p>Cons:</p><ul><li>Things aren’t always pluralized with an “s”, so $ doesn’t always make sense.</li><li>Why are we doing this with just observables? what about promises? or functions?</li><li>You have to reach for $ a lot on your keyboard (your IDE will probably solve this problem though)</li></ul><h4>Finnish-Goldman Notation</h4><h3>Sam Goldman on Twitter</h3><p>@BenLesh @_jayphelps @schwarty peopl€, mic€, oxe₦</p><p>This is a sub-dialect of Finnish notation. This dialect comes from <a href="https://twitter.com/nontrivialzeros">Sam Goldman</a>. The idea is that it addresses one of the problems listed above, that some words are not pluralized with an “s”. In Finnish-Goldman notation, what you do is pluralize observable variable names with a unicode character that matches the last letter of the pluralized word. For example:</p><pre>const oxeÑ = Observable.from(olleyOlleyOxenStream());<br>const mic€ = Observable.from(threeBlindStreams());<br>const peopl€ = Observable.from(allPeopleReadingThisNow());</pre><h4>So what do you choose???</h4><p>The jury is out. But choose wisely, the fate of your entire project, and perhaps the WORLD depends on using the proper variable naming conventions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8356ed1c9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[redux-observable]]></title>
            <link>https://benlesh.medium.com/redux-observable-ec0b00d2eb52?source=rss-da6839d28258------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0b00d2eb52</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Ben Lesh]]></dc:creator>
            <pubDate>Fri, 13 May 2016 01:39:24 GMT</pubDate>
            <atom:updated>2016-07-28T18:18:45.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*YFFWL4PhXKSDId3GEeRlYA.png" /></figure><p>Created by <a href="https://medium.com/u/5b0111cff646">Jay Phelps</a> and myself for use on our projects at Netflix, <a href="https://github.com/blesh/redux-observable">redux-observable </a>is middleware for redux that is inspired by <a href="https://github.com/gaearon/redux-thunk">redux-thunk</a>.</p><p><a href="https://github.com/blesh/redux-observable">redux-observable</a> allows developers to dispatch a function that returns an observable, promise or iterable of action(s). When the observable emits an action, or the promise resolves an action, or the iterable gives an action out, that action is then dispatched as usual.</p><p>This provides:</p><ul><li>The means to use reactive programming and composition to create async effects that dispatch actions to your redux reducer(s).</li><li>A straight-forward path for canceling those async actions via reactive composition.</li><li>A more explicit path to cancellation by calling `unsubscribe` on the subscription object returned from the dispatch.</li><li>A means of composing any actions together as individual streams with complex join operations like `zip` and `combineWith`.</li></ul><p>redux-observable is written with RxJS 5 under the hood and as such works with any observable type that implements `Symbol.observable`, such as <a href="https://github.com/reactivex/rxjs">RxJS</a>, <a href="https://github.com/rpominov/kefir">Kefir</a> and (soon) <a href="https://github.com/cujojs/most">Most</a>. However RxJS 5 is a peer dependency of redux-observable.</p><h3>NOTE: Some of what is below is outdated, please refer to the <a href="https://github.com/redux-observable/redux-observable#documentation">documentation</a> on Github</h3><h4>Technical Overview</h4><p>For a complete example I recommend checking out <a href="https://github.com/blesh/redux-observable/tree/master/examples/basic">the example provided in the repository</a>, but to cover basic usage, this is the general idea:</p><p>You can dispatch a function that returns any observable:</p><pre>const test = () =&gt; <br>  Observable.of({ type: ‘TEST’, data: ‘hello world’ });</pre><pre>dispatch(test);</pre><p>or any promise:</p><pre>const test = () =&gt; <br>  Promise.resolve({ type: ‘TEST’, data: ‘hello world’ });</pre><pre>dispatch(test);</pre><p>or any iterable (such as an array or generator):</p><pre>const manyActions = () =&gt; [{ type: &#39;TEST1&#39; }, { type: &#39;TEST2&#39; }];</pre><pre>dispatch(manyActions);</pre><p>When you dispatch a function, it returns a subscription object which can be used to cancel the async action. This allows you to explicitly unsubscribe from the async action at a later time and cancel it.</p><pre>const startTicking = () =&gt; <br>  Observable.interval(1000)<br>    .map((i) =&gt; ({ type: &#39;TICK&#39;, i });</pre><pre>const sub = dispatch(startTicking);</pre><pre><br>// later you can cancel the dispatched async action</pre><pre>sub.unsubscribe();</pre><p>However, that might not be the best approach. redux-observable also provides two arguments to the function you pass to `dispatch`. The first argument is an observable stream of all <em>future</em> actions dispatched. This enables the developer to compose a variety of complicated async behaviors together, including cancellation, which can be done via RxJS’s `takeUntil` operator. For ergonomics, the actions observable has an `ofType` operator to allow for cleaner filtering of specific types of actions dispatched.</p><pre>const startTicking = (actions, store) =&gt; <br>  Observable.interval(1000)<br>    .map((i) =&gt; ({ type: &#39;TICK&#39;, i }))<br>    .takeUntil(actions.ofType(&#39;STOP_TICK&#39;));</pre><pre>dispatch(startTicking);</pre><pre><br>// to stop the ticking actions at a later point</pre><pre>dispatch({ type: &#39;STOP_TICK&#39; });</pre><p>To be a little more holistic, here is an example of creating an ajax request that can be aborted by dispatching an abort action:</p><pre>// Just like normal redux, we&#39;re now using an action factory<br>// so that we can create a one-off observable that relies on userId</pre><pre>const fetchUserById = (userId) =&gt; (<br>  (actions) =&gt; (<br>    Observable.ajax(`/api/users/${userId}`)<br>      .map(<br>        (payload) =&gt; ({ type: &#39;FETCH_USER_FULFILLED&#39;, payload })<br>      )<br>      .takeUntil(actions.ofType(&#39;FETCH_USER_ABORT&#39;))<br>      .startWith({ type: &#39;FETCH_USER_PENDING&#39; })<br>  )<br>);<br><br>const subscription = dispatch(fetchUserById(1));<br></pre><pre>// To cancel the AJAX request you can dispatch an abort action<br>// from anywhere in your app</pre><pre>dispatch({ type: &#39;FETCH_USER_ABORT&#39; });</pre><pre><br>// or if it happens to be more ergonomic, just unsubscribe<br>// directly. Sometimes you want to abort all of these,<br>// sometimes just this single one.</pre><pre>subscription.unsubscribe();</pre><h4>Origins</h4><p>Originally the react-based dataviz apps that Jay and I were working on here at Netflix were using plain React idioms like passing props and `setState` to manage state in our views. While this worked and was reasonably ergonomic, we quickly found ourselves in the weeds as some of our more complicated views and visualizations grew.</p><p>We looked into other solutions like redux-thunk and redux-saga, but given that we really love Rx and like to use reactive programming to solve the complicated async problems presented by real-time dataviz apps, we decided to try to create a new middleware that cleanly solved our problem using RxJS 5.</p><h4>Why Redux? Why not RxJS 5?</h4><p>Given that “Redux can be written in a few lines of Rx using the scan operator”, why use Redux at all?</p><p>The answer to this is pretty simple: Redux has a well defined existing pattern and guidance for use within React. More importantly, Redux has a lot of nice community-driven tooling that we wanted to be able to take advantage of. At the end of the day, it doesn’t matter if the reducers are run via an Rx `scan` or Redux. What matters is the productivity and performance and Redux and Redux’s tooling provides those two things well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0b00d2eb52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>