<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Reactive Programming - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Reactive Programming - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 09 Jul 2026 23:07:01 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/reactive-programming/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Understand RxJS Operators by Eating a Pizza: zip, forkJoin, & combineLatest Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Samuel Teboul What is RxJS? Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change - Wikipedia RxJS is a library for reactive programming using observables that makes it easier to co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understand-rxjs-operators-by-eating-a-pizza/</link>
                <guid isPermaLink="false">66d460eef855545810e934d5</guid>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 13 May 2020 18:44:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/download.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Samuel Teboul</p>
<h1 id="heading-what-is-rxjs">What is RxJS?</h1>
<blockquote>
<p><em>Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change</em> - <strong>Wikipedia</strong></p>
<p>RxJS is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code - <strong>RxJS docs</strong></p>
</blockquote>
<p>The essential concepts in RxJS are</p>
<ul>
<li><strong>An Observable</strong> is a stream of data</li>
<li><p><strong>Observers</strong> can register up to 3 callbacks:</p>
</li>
<li><p><em>next</em> is called 1:M time to push new values to the observer</p>
</li>
<li><em>error</em> is called at most 1 time when an error occurred</li>
<li><p><em>complete</em> is called at most 1 time on completion</p>
</li>
<li><p><strong>Subscription</strong> "kicks off" the observable stream</p>
</li>
</ul>
<p>Without subscribing the stream won't start emitting values. This is what we call a <strong>cold</strong> <strong>observable.</strong> </p>
<p>It's similar to subscribing to a newspaper or magazine... you won't start getting them until you subscribe. Then, it creates a 1 to 1 relationship between the producer (observable) and the consumer (observer).</p>
<p><img src="https://lh3.googleusercontent.com/_ro6f-oBp5o-e98sRUYOhfC6T_j79UOqNyfzLse5MfSs4WItSaYoHHK6TS7MlN1O5pSZsN98hA6af6L0j_MHh5F7bL8_Vm3fiya9Vw3Xwr4E0DI9IijKqN6VivRX__bkw7ze30EnzjY" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-what-are-rxjs-operators">What are RxJS operators?</h1>
<p>Operators are pure functions that enable a functional programming style of dealing with collections with operations. There are two kinds of operators:</p>
<ul>
<li>Creation operators</li>
<li>Pipeable operators: transformation, filtering, rate limiting, flattening</li>
</ul>
<p>Subjects are a special type of Observable that allows values to be <strong>multicast</strong> to many Observers. While plain Observables are <strong>unicast</strong> (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. This is what we call a <strong>hot</strong> <strong>observable.</strong></p>
<p>In this article, I will focus on the <code>zip</code>, <code>combineLatest</code> and <code>forkJoin</code> operators. These are RxJS combination operators, which means that they enable us to join information from multiple observables. Order, time, and structure of emitted values are the primary differences among them.</p>
<p>Let's look at each one individually.</p>
<h1 id="heading-zip">zip()</h1>
<ul>
<li><code>zip</code> doesn’t start to emit until each inner observable emits at least one value</li>
<li><code>zip</code> emits as long as emitted values can be collected from all inner observables</li>
<li><code>zip</code> emits values as an array</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_oY4pB5RbNeloyauM1tpWmg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let’s imagine that you are with Mario and Luigi, two of your best friends, at the best Italian restaurant in Rome. Each one of you orders a drink, a pizza, and a dessert. You specify to the waiter to bring the drinks first, then the pizzas, and finally the desserts.</p>
<p>This situation can be represented with 3 different observables, representing the 3 different orders. In this specific situation, the waiter can use the <code>zip</code> operator to bring (emit) the different order items by category.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_ve5RtSu2eH7b3pe8lJQ9rg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<p>If you go back to the same Italian restaurant with your girlfriend, but she doesn’t want to eat, this is what will happen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_8g5NLq3fTBekvu6gvnfJcw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If the <code>waiter$</code> uses the <code>zip</code> operator, you will only get your drink!</p>
<p>Why?</p>
<p>Because, when the <code>waiter$</code> emits the drinks, the <code>girlfriend$</code> observable is complete and no more value can be collected from it. Hopefully, the <code>waiter$</code> can use another operator for us so we don't break up with our girlfriend ?</p>
<h1 id="heading-combinelatest">combineLatest()</h1>
<ul>
<li><code>combineLatest</code> doesn’t start to emit until each inner observable emits at least one value</li>
<li>When any inner observable emits a value, emit the last emitted value from each</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_TrJG2NP6PgA0HJMj598lpQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At the exact same restaurant, the smart <code>waiter$</code> now decide to use <code>combineLatest</code> operator.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_GHNM2srLwN4Wihm7U8bcQg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<p>With <code>combineLatest</code>, the <strong>order</strong> of the provided inner observables does matter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If <code>you$</code> is provided first to <code>waiter$</code>, it will emit only one value <code>["Tiramisu", "Sprite"]</code>. </p>
<p>This is happening because <code>combineLatest</code> doesn’t start to emit until each inner observable emits at least one value. <code>girlfriend$</code> starts emitting when the first inner observable emits its last value. Then, <code>combineLatest</code> emits the last values collected from both inner observables.</p>
<h1 id="heading-forkjoin">forkJoin()</h1>
<ul>
<li><code>forkJoin</code> emits the last emitted value from each inner observables after they <strong>all</strong> complete</li>
<li><code>forkJoin</code> will never emit if one of the observables doesn’t complete</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_O-Uis5OrgaeUrh6JSgHkTg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When you go to the restaurant and order for a pizza, you don’t want to know all the steps about how the pizza is prepared. If the cheese is added before the tomatoes or the opposite. You just want to get your pizza! This is where <code>forkJoin</code> comes into play.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_tB1kiVeQ2kpicnNjFnN_dA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>❗️❗️❗️Warning❗️❗️❗️</strong></p>
<ul>
<li>If one of the inner observables throws an error, all values are lost</li>
<li><code>forkJoin</code> doesn’t complete</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_zLaN2lzWlASOC3X7f-k3kA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>If you are only concerned when <strong>all</strong> inner observables complete successfully, you can catch the error from the <strong>outside</strong></li>
<li>Then, <code>forkJoin</code> completes</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>If you don’t care that inner observables complete successfully or not, you must catch errors from every single inner observable</li>
<li>Then, <code>forkJoin</code> completes</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Personally, when I go to a restaurant with friends, I don’t care if one of them receives a burnt pizza. I just want mine ? so I will ask the <code>waiter$</code> to catch the errors from inner observables individually.</p>
<h1 id="heading-wrap-up">Wrap up</h1>
<p>We covered a lot in this article! Good examples are important to better understand RxJS operators and how to choose them wisely. </p>
<p>For combination operators like <code>zip</code>, <code>combineLatest</code>, and <code>forkJoin</code> the order of inner observables that you provide is also critical, as it can drives you to unexpected behaviours.</p>
<p>There is much more to cover within RxJS and I will do it in further articles.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/1_RHYpi9BEvKatE0NRsHfnOw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I hope you enjoyed this article! ?</p>
<p>? You can <a target="_blank" href="https://twitter.com/tSamoss">follow me on Twitter</a> to get notified about new Angular/RxJS blog posts and cool tips!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Tips to Enhance the Performance of Your React App ]]>
                </title>
                <description>
                    <![CDATA[ By Shifa Martin ReactJS is an open-source framework that facilitates the development of UI interfaces for web and mobile applications. Developers globally use the framework to build state-of-the-art applications which subsequently generate revenues a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tips-to-enhance-the-performance-of-your-react-app/</link>
                <guid isPermaLink="false">66d460fa4a0edd9b48e83589</guid>
                
                    <category>
                        <![CDATA[ create-react-app ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react testing library ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Aug 2019 13:46:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/08/react.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shifa Martin</p>
<p>ReactJS is an open-source framework that facilitates the development of UI interfaces for web and mobile applications. Developers globally use the framework to build state-of-the-art applications which subsequently generate revenues as well as expand the audience for businesses.  </p>
<p>However, building a great UI with React isn’t enough, You’ve got to add that extra glitter to make the app more polished, functional and remarkably better than the competition. </p>
<p>This is exactly what I’m going to help you with as I describe some key methods to increase performance in React apps.</p>
<h3 id="heading-1-making-good-use-of-identities">1. Making good use of Identities</h3>
<p>When building mobile apps with React,  it is possible to wrap functions and variables with React.useMemo. Doing so provides the ability to memoize them so they remain identical for renders in the future.  </p>
<p>When functions and variables are not memoized, any references to them might vanish from future renders. Memoizing helps in negating wasteful processes and operations in every situation where you’d leverage functions and variables.</p>
<p><em><strong>Example:</strong></em> </p>
<p>Say, we’re preparing a custom hook for a list of urls as arguments. Using the hook, we can collect them into an array of promise objects and resolve them with Promise.all. The results of this accumulation will enter the state and be passed the app component once done. The list of promises now map over the urls array from where it fetches the urls.</p>
<pre><code class="lang-react">import React from 'react'
import axios from 'axios'

export const useApp = ({ urls }) =&gt; {
  const [results, setResults] = React.useState(null)

  const promises = urls.map(axios.get)

  React.useEffect(() =&gt; {
    Promise.all(promises).then(setResults)
  }, [])

  return { results }
}

const App = () =&gt; {
  const urls = [
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=a',
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=b',
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=c',
  ]

  useApp({ urls })

  return null
}

export default App
</code></pre>
<p>Since we want to obtain data from 3 urls here, only 3 requests are supposed to be sent out, one for each url. However,  when looking at it through the inspect element feature on Google Chrome, we find that 6 requests are sent instead of the supposed 3.<br>This happens because the urls argument did not retain its previous identity. When the app is re-rendered, it’s instantiating a new array each time, as React treats it as a different value.  </p>
<p><img src="https://lh5.googleusercontent.com/XE6rCdOL110eYARSgVTgcwiecF2qNAT96yBYn_-FbQ2_ffjdRAplLqRxu4eQh-NniyF0doEPRtsT3X0lYxeHcSu35UN0giiteCsIJTrVP9tw1mITk5-P5hH3PmdWd2ss5R0E2pb3" alt="Image" width="665" height="160" loading="lazy"></p>
<p>To fix this problem, we can use React.useMemo as previously mentioned. When using React.useMemo, the array of promise objects won’t recompute in each new render unless the array with the list of urls changes. As long as it stays the same, the identities remain.</p>
<p><strong>Here’s what happens when applying React.useMemo to this example:</strong></p>
<pre><code class="lang-react">const useApp = ({ urls }) =&gt; {
  const [results, setResults] = React.useState(null)

  const promises = urls.map((url) =&gt; axios.get(url))

  React.useEffect(() =&gt; {
    Promise.all(promises).then(setResults)
  }, [])

  return { results }
}

const App = () =&gt; {
  const urls = React.useMemo(() =&gt; {
    return [
      'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=a',
      'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=b',
    ]
  }, [])

  const { results } = useApp({ urls })

  return null
}
</code></pre>
<p>It will send 6 requests even now since we’ve only memoized the urls array. The promises variables are also instantiating when running the hook. So in order to send only 3  requests, we also have to memorize the promises variables as well.</p>
<pre><code class="lang-react">const promises = React.useMemo(() =&gt; {
  return urls.map((url) =&gt; axios.get(url))
}, [urls])
</code></pre>
<blockquote>
<p>After memoizing both the urls array and the promises variables, this is what we get: </p>
</blockquote>
<p><img src="https://lh4.googleusercontent.com/P-8qvsq_Nu229Eod2_FIlqLtY1_lAxkPXZfw3a9D7P25VIyGrw--kTnOuTF4rmXPsA3vxGRifwprsI_VGGDU9pFIafOAsfPKiQE3L3Zv1MHXzPH25e2g39MaCikn2AActzgJlftr" alt="Image" width="740" height="162" loading="lazy"></p>
<h3 id="heading-2-merging-props-to-children">2. Merging Props to Children</h3>
<p>At times, developers get into situations where they prefer merging a prop with children before rendering. To facilitate the same, React allows viewing the props to all react elements including others, and also allows exposing their key.</p>
<p>So developers can choose to wrap the children element with a newer one, and insert new props there or they can simply merge the props with React.</p>
<p>Say, we have an app component that uses a useModal and offers the ability to manage modals by using controls such as open, close, opened and activated. Before merging props to children, we can pass them to a VisbilityControl component which provides some additional functionality.</p>
<pre><code class="lang-react">import React from 'react'

const UserContext = React.createContext({
  user: {
    firstName: 'Kelly',
    email: 'frogLover123@gmail.com',
  },
  activated: true,
})

const VisibilityControl = ({ children, opened, close }) =&gt; {
  const ctx = React.useContext(UserContext)
  return React.cloneElement(children, {
    opened: ctx.activated ? opened : false,
    onClick: close,
  })
}

export const useModal = ({ urls } = {}) =&gt; {
  const [opened, setOpened] = React.useState(false)
  const open = () =&gt; setOpened(true)
  const close = () =&gt; setOpened(false)

  return {
    opened,
    open,
    close,
  }
}

const App = ({ children }) =&gt; {
  const modal = useModal()

  return (
    &lt;div&gt;
      &lt;button type="button" onClick={modal.opened ? modal.close : modal.open}&gt;
        {modal.opened ? 'Close' : 'Open'} the Modal
      &lt;/button&gt;
      &lt;VisibilityControl {...modal}&gt;{children}&lt;/VisibilityControl&gt;
    &lt;/div&gt;
  )
}

const Window = ({ opened }) =&gt; {
  if (!opened) return null
  return (
    &lt;div style={{ border: '1px solid teal', padding: 12 }}&gt;
      &lt;h2&gt;I am a window&lt;/h2&gt;
    &lt;/div&gt;
  )
}

export default () =&gt; (
  &lt;App&gt;
    &lt;Window /&gt;
  &lt;/App&gt;
)
</code></pre>
<p>Using Visibility control allows developers to ascertain whether the control activated is true before allowing the control opened to be used by children. In case the Visibility Control feature is used via a secret route, there’s an option to prevent unactivated users from accessing the content.  </p>
<h3 id="heading-3-making-a-larger-reducer">3. Making a larger reducer</h3>
<p>It is possible to combine to or more reducer to make a single, much larger reducer that can help boost a react app.</p>
<p>Say, you think of building a large app that provides access to a wide variety of small services. How would you go about the development of such an app? </p>
<p><strong>There are two options:</strong></p>
<ol>
<li>We can give each microservice within the app a separate part of its own from where its state and context can be managed directly.  </li>
</ol>
<ol start="2">
<li>Or we can combine all states into a single large state and manage all of them within the same environment.  </li>
</ol>
<blockquote>
<p>The first approach seems to highly tedious, so obviously, the second one is the way to go.  </p>
</blockquote>
<p><strong>Now we have three reducers to combine -</strong> </p>
<p>frogsreducer.js, authreducer.js and finally, ownersreducer.js.  </p>
<p><strong>Let's start with authReducer.js</strong></p>
<pre><code class="lang-react">const authReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'set-authenticated':
      return { ...state, authenticated: action.authenticated }
    default:
      return state
  }
}

export default authReducer

ownersReducer.js
</code></pre>
<p><strong>ownersReducer.js</strong></p>
<pre><code class="lang-react">const ownersReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'add-owner':
      return {
        ...state,
        profiles: [...state.profiles, action.owner],
      }
    case 'add-owner-id':
      return { ...state, ids: [...state.ids, action.id] }
    default:
      return state
  }
}

export default ownersReducer
</code></pre>
<p><strong>frogsReducer.js</strong></p>
<pre><code class="lang-react">const frogsReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'add-frog':
      return {
        ...state,
        profiles: [...state.profiles, action.frog],
      }
    case 'add-frog-id':
      return { ...state, ids: [...state.ids, action.id] }
    default:
      return state
  }
}

export default frogsReducer
</code></pre>
<blockquote>
<p>Now we can put all three into the main app file and define their state:  </p>
</blockquote>
<p><strong>App.js</strong></p>
<pre><code class="lang-react">import React from 'react'
import authReducer from './authReducer'
import ownersReducer from './ownersReducer'
import frogsReducer from './frogsReducer'

const initialState = {
  auth: {
    authenticated: false,
  },
  owners: {
    profiles: [],
    ids: [],
  },
  frogs: {
    profiles: [],
    ids: [],
  },
}

function rootReducer(state, action) {
  return {
    auth: authReducer(state.auth, action),
    owners: ownersReducer(state.owners, action),
    frogs: frogsReducer(state.frogs, action),
  }
}

const useApp = () =&gt; {
  const [state, dispatch] = React.useReducer(rootReducer, initialState)

  const addFrog = (frog) =&gt; {
    dispatch({ type: 'add-frog', frog })
    dispatch({ type: 'add-frog-id', id: frog.id })
  }

  const addOwner = (owner) =&gt; {
    dispatch({ type: 'add-owner', owner })
    dispatch({ type: 'add-owner-id', id: owner.id })
  }

  React.useEffect(() =&gt; {
    console.log(state)
  }, [state])

  return {
    ...state,
    addFrog,
    addOwner,
  }
}

const App = () =&gt; {
  const { addFrog, addOwner } = useApp()

  const onAddFrog = () =&gt; {
    addFrog({
      name: 'giant_frog123',
      id: 'jakn39eaz01',
    })
  }

  const onAddOwner = () =&gt; {
    addOwner({
      name: 'bob_the_frog_lover',
      id: 'oaopskd2103z',
    })
  }

  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;button type="button" onClick={onAddFrog}&gt;
          add frog
        &lt;/button&gt;
        &lt;button type="button" onClick={onAddOwner}&gt;
          add owner
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/&gt;
  )
}
export default () =&gt; &lt;App /&gt;

This is what it looks like combining all three reducers into one large reducer, along with rootReducer

function rootReducer(state, action) {
  return {
    auth: authReducer(state.auth, action),
    owners: ownersReducer(state.owners, action),
    frogs: frogsReducer(state.frogs, action),
  }
</code></pre>
<p>This is what it looks like combining all three reducers into one large reducer, along with rootReducer.</p>
<h3 id="heading-using-sentry-for-analyzing-errors">Using Sentry for Analyzing Errors</h3>
<p><img src="https://lh5.googleusercontent.com/ySh7MjcCdU2XUVc1GASq8HBz0ym9Yn3mQt8xP0fygcYWqf-UoSkOAV1gOxUSgOQ3o79FJb7R3P9iwIYngWY8MtNB6uAqHBh-UXY5gf_G-C9kN_Nuxx73iYllkPSqKKOSjDTXWvmb" alt="Image" width="1544" height="770" loading="lazy"></p>
<p>Any mobile app development project can benefit greatly from <a target="_blank" href="https://sentry.io/welcome/">Sentry.</a> It provides everything a developer needs to handle errors and exceptions when building apps with React. Sentry identifies all errors and displays them at one central location so they can be accessed and analyzed all at once.</p>
<p>Getting started with Sentry on React is easy. Just use npm install @sentry/browser and set it up. Once done, developers can log in at sentry.io and analyze all error reports of a project on a single dashboard.</p>
<p>The error reports from sentry are incredibly detailed. They provide all sorts of important information which include the user’s device information, browser, URL, stack trace, how the error was handled, source code, IP address, breadcrumbs to trace the source of error, the error function name and much more.  </p>
<h3 id="heading-5-using-axios-for-http-requests">5. Using Axios for HTTP requests</h3>
<p>Though <a target="_blank" href="https://github.com/axios/axios">Axios</a> is commonly used for HTTP requests. I felt it is important to mention this point because it's actually not common for developers to use other request libraries such as fetch for React apps.  </p>
<p>Windows.fetch provides no support for Internet Explorer 11 (most don’t really care though). But for what it's worth, Axios does work there as well and offers the ability to cancel requests in mid-flight.  </p>
<h3 id="heading-final-words">Final Words</h3>
<p>The 5 mentioned methods can greatly help speed up your React app. It helps developers, the business you’re in and of course, those who’d be using it eventually. But honestly, the success of your React App mostly depends on those who work on them. </p>
<p>As a consumer, you’d want better performance from your app, so it is what denotes success. As a developer, these methods could make your app easier to develop, and efficiency is key to being more productive. </p>
<p><strong>ValueCoders is an expert <a target="_blank" href="https://www.valuecoders.com/">IT outsourcing company</a> for software development. If you are looking for offshore React programmers or <a target="_blank" href="https://www.valuecoders.com/hire-developers/hire-android-developers">hire Android developers</a>, feel free to get in touch.</strong> </p>
<p>Also, I hope this post helps you learn new things and get a deeper insight into what goes into making the perfect react application. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Subjects in Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Dler Ari A Subject is a “special” type of observable that allows us to broadcast values to multiple subscribers. The cool thing about Subjects, is that it provides a real-time response. For instance, if we have a subject with 10 subscribers, whene... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-subjects-in-reactive-programming-bbdc8fed7b6/</link>
                <guid isPermaLink="false">66d45e47d14641365a0508b8</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ observables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 28 Mar 2019 16:15:19 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*6gi30QcIoPkwcxpz5d4wkg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dler Ari</p>
<p>A Subject is a “special” type of observable that allows us to broadcast values to multiple subscribers. The cool thing about Subjects, is that it provides a real-time response.</p>
<p>For instance, if we have a subject with 10 subscribers, whenever we push values to the subject, we can see the value captured by each subscriber</p>
<p>This introduces a couple challenges; what if we push some values, and then subscribe, or vice-verse? Timing plays an important role, if we subscribe late, we won’t be able to access the values, similar to if someone enters a live-sport event on TV 30 minutes later.</p>
<p>Luckily, we have 4 types of Subjects that allows us to “time travel” in which we can access values even though we subscribe late or not.</p>
<h4 id="heading-topics-well-cover">Topics we’ll cover:</h4>
<ol>
<li>What is a Subject with a practical example</li>
<li>BehaviorSubject: Get the last message</li>
<li>ReplaySubject: Time travel</li>
<li>AsyncSubject: Once completed, get the last message</li>
</ol>
<h3 id="heading-1-what-is-a-subject">1. What is a Subject?</h3>
<p>As mentioned, a Subject is nothing more like an observable with a few more characteristics. An observable is by definition an <a target="_blank" href="https://rxjs.dev/guide/overview">invokable collection</a> that emits data once subscribed. Meanwhile, a Subject is where we control the state of “when to emit data” to multiple subscribers.</p>
<p>A Subject allows us to invoke methods like <code>.next()</code>, <code>.complete()</code> and <code>.error()</code> outside, while in an observable, we invoke these methods as callbacks.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Creating an Observable</span>
<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function">(<span class="hljs-params">observer</span>) =&gt;</span> {
    observer.next(<span class="hljs-number">10</span>);
    observer.next(<span class="hljs-number">5</span>);
    observer.complete();
});

<span class="hljs-comment">// Creating a Subject</span>
<span class="hljs-keyword">const</span> subject = <span class="hljs-keyword">new</span> Subject();
subject.next(<span class="hljs-number">10</span>);
subject.next(<span class="hljs-number">5</span>);
subject.complete();
</code></pre>
<h4 id="heading-practical-example-lets-build-a-simple-chat-group-using-a-subject">Practical example: Let’s build a simple chat group using a Subject</h4>
<p>Let’s imagine we are building a simple chat app where people can post messages to the chat group. The first step is to create an instance of the Subject, and then assign it to a <code>chatGroup</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create subject "Observable"</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> Subject();
</code></pre>
<p>Now that our chat group (Subject) is created, the next thing to do is add messages. Let’s create a typical conversation between two friends.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Push values to the stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);
</code></pre>
<p>So far so good — now we have 4 messages posted in our chat group, so what happens if we subscribe? Or let’s say a new friend named John wants to join the conversation. Is he be able to see the old messages?</p>
<pre><code class="lang-js"><span class="hljs-comment">// Print messages</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})
</code></pre>
<p>Unfortunately not, John misses the conversation because he’s subscribes late. This is a perfect example of how reactive programming works — the idea of values passing over time, and thus, we must subscribe in the right time to access the values.</p>
<p>To further elaborate on the previous example, what if John enters in the middle of the conversation?</p>
<pre><code class="lang-js"><span class="hljs-comment">// Push values to the stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);

<span class="hljs-comment">// John enters the conversation </span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
});

chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// David - Interesting, which one is the hottest?</span>
<span class="hljs-comment">// Peter - Game of Thrones!</span>
</code></pre>
<p>Once John subscribes, he sees the two last messages. The Subject is doing what it’s intended to do. But what if we want John to view all messages, or just the last one, or get notified when a new message is posted?</p>
<p>In general, these Subjects are mostly similar, but each one provides some extra functionality, let’s describe them one by one.</p>
<h3 id="heading-2-behaviorsubject-get-last-message">2. BehaviorSubject: Get last message</h3>
<p>The BehaviorSubject is similar to a Subject except it requires an initial value as an argument to mark the starting point of the data stream. The reason is because when we subscribe, it returns the last message. This is similar concept when dealing with arrays; where we do <code>array.length-1</code> to get the latest value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {BehaviorSubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> BehaviorSubject(<span class="hljs-string">'Starting point'</span>);

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// Peter - Game of Thrones!</span>
</code></pre>
<h3 id="heading-3-replaysubject-time-travel">3. ReplaySubject: Time travel</h3>
<p>The ReplaySubject, as the name implies, once subscribed it broadcasts all messages, despite if we subscribed late or not. It’s like time travel, where we can access all the values that were broadcast.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">import</span> { ReplaySubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> ReplaySubject();

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// David - Hi, which hot series do you recommend?'</span>
<span class="hljs-comment">// Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>
<span class="hljs-comment">// David - Interesting, which one is the hottest?'</span>
<span class="hljs-comment">// Peter - Game of Thrones!'</span>
</code></pre>
<h3 id="heading-4-asyncsubject-once-completed-get-last-message">4. AsyncSubject: Once completed, get last message</h3>
<p>The AsyncSubject is similar to BehaviorSubject in terms of emitting the last value once subscribed. The only difference is that it requires a <code>complete()</code> method to mark the stream as completed. Once that is done, the last value is emitted.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { AsyncSubject } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-comment">// Create a Subject</span>
<span class="hljs-keyword">const</span> chatGroup = <span class="hljs-keyword">new</span> AsyncSubject();

<span class="hljs-comment">// Push values to the data stream</span>
chatGroup.next(<span class="hljs-string">'David - Hi, which hot series do you recommend?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones, Bodyguard or Narcos are few of the good ones'</span>);
chatGroup.next(<span class="hljs-string">'David - Interesting, which one is the hottest?'</span>);
chatGroup.next(<span class="hljs-string">'Peter - Game of Thrones!'</span>);

chatGroup.complete(); <span class="hljs-comment">// &lt;-- Mark the stream as completed</span>

<span class="hljs-comment">// John enters the conversation</span>
chatGroup.subscribe(<span class="hljs-function">(<span class="hljs-params">messages</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(messages)
})

<span class="hljs-comment">// OUTPUT</span>
<span class="hljs-comment">// Peter - Game of Thrones!'</span>
</code></pre>
<h3 id="heading-summary">Summary</h3>
<p>Back to our previous example with John, we can now decide if we want John to access the whole conversation (ReplaySubject), the last message (BehaviorSubject), or the last message once the conversation completes (AsyncSubject).</p>
<p>If you ever struggle to identify if a Subject is the right way to go, the article “<a target="_blank" href="http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx">To Use a Subject or Not to Use a Subject</a>” by Dave Sixton describes when to use Subjects based on two criteria:</p>
<ol>
<li>Only when one want to <strong>convert</strong> a cold Observable into a hot observable.</li>
<li><strong>Generate</strong> a hot observable that passes data continuously.</li>
</ol>
<p>In short, only creativity limits the potential use of reactive programming. There will be some scenarios where Observables do most of the heavy-lifting, but understanding what Subjects are, and what type of Subjects exists, will definitely improve your reactive programming skills.</p>
<p>If you are interested to learn more about the web-ecosystem, here are few articles I’ve written, enjoy.</p>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-comparison-between-angular-and-react-and-their-core-languages-9de52f485a76">A comparison between Angular and React</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773">A practical guide to ES6 modules</a></li>
<li>[How to perform HTTP requests using the Fetch API](http://A practical ES6 guide on how to perform HTTP requests using the Fetch API)</li>
<li><a target="_blank" href="https://medium.freecodecamp.org/learn-these-core-javascript-concepts-in-just-a-few-minutes-f7a16f42c1b0?gi=6274e9c4d599">Important web concepts to learn</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/7-javascript-methods-that-will-boost-your-skills-in-less-than-8-minutes-4cc4c3dca03f">Boost your skills with these JavaScript methods</a></li>
<li><a target="_blank" href="https://codeburst.io/learn-how-to-create-custom-bash-commands-in-less-than-4-minutes-6d4ceadd9590">Create custom bash commands</a></li>
</ul>
<p>You can find me on Medium where I publish on a weekly basis. Or you can follow me on <a target="_blank" href="http://twitter.com/dleroari">Twitter</a>, where I post relevant web development tips and tricks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to observables in Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Dler Ari One of the most challenging things for new developers to learn is the observer pattern. Understanding how to effectively use it with RxJS to deal with asynchronous data such as user events, HTTP requests or any other events that require w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-observables-in-reactive-programming-1cfd3e23bb94/</link>
                <guid isPermaLink="false">66d45e45182810487e0ce157</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 22 Mar 2019 16:40:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*5FEY_E1x_bCfWpz3RiIFXw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dler Ari</p>
<p>One of the most challenging things for new developers to learn is the observer pattern. Understanding how to effectively use it with RxJS to deal with asynchronous data such as user events, HTTP requests or any other events that require waiting for something to complete is tricky.</p>
<p>What most people struggle with is the new approach. It requires a different mindset where visualization plays an important role. We think of data as a sequence of values that passes over time rather than as one single value that is retrieved once. This mindset is known as reactive programming.</p>
<p>Since the Observer pattern is a fairly large ecosystem consisting of many important parts, I’ve chosen to narrow it down by focusing on Observables only. I’ll share other articles soon that cover the rest of the Observer pattern, such as how to deal with RxJS.</p>
<h4 id="heading-topics-well-cover">Topics we’ll cover:</h4>
<ol>
<li>What does asynchronous really mean?</li>
<li>Which pattern to use (Observer or Promise)</li>
<li>How to create an Observable (code examples start here)</li>
<li>How to subscribe to an Observable</li>
<li>How to unsubscribe to an Observable</li>
</ol>
<h3 id="heading-1-what-does-asynchronous-really-mean">1. What does asynchronous really mean?</h3>
<p>One of the things with the web, and the majority of languages, is that once you ask for data such as requesting a list of users from the server, you can’t guarantee that the data will be returned. There is an uncertainty issue.</p>
<p>One of the reasons may be that the data is not present, the server may be broken, or the HTTP URL is not valid because someone has changed the query string.</p>
<p>For that reason, along with a few others, we need to deal with such data asynchronously. We request the list of users, and wait until it is retrieved, but don’t stop the whole application for a simple operation.</p>
<p>It’s like telling a coworker to solve a task instead of sending the whole team; that would be an expensive and not a wise approach to take.</p>
<p>Let’s clarify a misconception: the terms synchronous or asynchronous have nothing to do with multi-threading, where operations are executed at the same time. It simply means the operations are either <strong>dependent on</strong> or <strong>independent from</strong> each other, that’s it.</p>
<p>Let’s compare the difference between synchronous and asynchronous to better understand how they really work.</p>
<h4 id="heading-what-is-synchronous">What is Synchronous?</h4>
<p>With Synchronous events, you wait for one to finish before moving on to another task.</p>
<p><strong>Example:</strong> You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you. Answered by <a target="_blank" href="https://stackoverflow.com/users/1428344/themightysapien">themightysapien</a>.</p>
<h4 id="heading-what-is-asynchronous">What is Asynchronous?</h4>
<p>With asynchronous events, you don’t wait, you can move on to the next task until the data is available.</p>
<p><strong>Example:</strong> You are in a restaurant with many other people. You order your food. Other people can also order their food, they don’t have to wait for your food to be cooked and served to you before they can order. In the kitchen, restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked. Answered by <a target="_blank" href="https://stackoverflow.com/users/1428344/themightysapien">themightysapien</a>.</p>
<p>Alright, so in short, this allows us to either wait for operations to happen before we can move on, or not wait until the data is ready.</p>
<h3 id="heading-2-which-pattern-to-use-observer-or-promise">2. Which pattern to use (Observer or Promise)</h3>
<p>First of all, both the observer pattern and the promise pattern deal with asynchronous operations. Operations such as user events or HTTP requests, or any other events that execute independently.</p>
<p>The majority of operations today need some type of asynchronous/synchronous handling, and understanding how it works plays an important role when building robust apps.</p>
<p>It’s not meant to make your life harder, but easier. However, it thus requires a learning-curve which may be a painful approach, but the reward at the end is well worth it.</p>
<h4 id="heading-stay-with-one-pattern">Stay with one pattern</h4>
<p>The difference lies in the complexity of the application. If you deal with a small app where the task is to simply get a list of users from the server, or to show active members, then promises with the <code>Fetch API</code> (<a target="_blank" href="https://medium.freecodecamp.org/a-practical-es6-guide-on-how-to-perform-http-requests-using-the-fetch-api-594c3d91a547">read more</a>) work fine.</p>
<p>But if you deal with a large application with many asynchronous operations that require changing the data, performing multiple operations on a data stream, or reusing it in multiple places, then the observer pattern works great.</p>
<h4 id="heading-can-i-use-both-patterns-in-one-project">Can I use both patterns in one project?</h4>
<p>Yes, but it’s not recommended that you mix between two architectures which basically do the same thing (handle asynchronous events). Instead, stick with one, and learn more about it.</p>
<h4 id="heading-boost-your-skills-with-rxjs">Boost your skills with RxJS</h4>
<p>With RxJS, you have access to 189 operators with documentation + <a target="_blank" href="https://reactive.how/">other great resources</a>. And each of these operators are simply callbacks that do something on the data stream.</p>
<p>If you are familiar with JavaScript’s functional prototypes (methods) such as <code>map()</code>, <code>filter()</code>, and <code>reduce()</code>, you’ll find them in RxJS. Note, the concept is the same but the written code is not.</p>
<p>So what is the difference between these two patterns?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*EAzaxT7ejRGLcvL4pgVqPA.png" alt="Image" width="554" height="316" loading="lazy">
<em>Observable vs Promise</em></p>
<p>Here’s a quick comparison between the observer pattern and the promise pattern. The key points are that a promise emits a single value(s) once the <code>.then()</code> callback is used, while an Observable emits multiple values as a sequence of data that passes over time. Another important point is that an Observable can be canceled or retried while a promise cannot. However, there are external packages that make it possible to cancel a promise.</p>
<h3 id="heading-3-how-do-we-create-an-observable">3. How do we create an Observable?</h3>
<p>Here are a couple of ways one can create an Observable:</p>
<ul>
<li>create an Observable from scratch</li>
<li>turn a promise into an Observable</li>
<li>or use a framework that does it for you behind the scenes, such as Angular.</li>
</ul>
<blockquote>
<p>Did you know that Angular uses the Observer pattern extensively? All asynchronous operations such as HTTP GET or listening for events or value changes follow the observer pattern.</p>
</blockquote>
<p>If you ever want to mimic (test) a real-world scenario, so to say pass values over time, I highly recommend using the interval function. This passes values after x time in milliseconds. So if you have an interval where x is 2000ms — it passes each value (increments) after 2 seconds.</p>
<h3 id="heading-4-how-do-we-subscribe-to-an-observable">4. How do we subscribe to an Observable?</h3>
<p>An Observable is simply a collection of data that waits to be invoked (subscribed) before it can emit any data. If you’ve worked with promises, then the way to access the data is to chain it with the <code>then()</code> operator or use the ES6 <code>async/await</code>.</p>
<p>So to follow the previous example, how does one access the data?</p>
<p>As shown above, when we subscribe, we tell the Observable to pass us whatever it holds. It can be an array, a collection of events, or a sequence of objects and so forth.</p>
<p>A common beginner-mistake I’ve seen among developers is that they do many operations on the Observable but get frustrated because they can’t see any results. You are not alone! I’ve made this mistake a couple of times and as a thumb-rule — always remember to subscribe.</p>
<h3 id="heading-5-how-do-we-unsubscribe-to-an-observable">5. How do we unsubscribe to an Observable?</h3>
<p>It is important to unsubscribe, otherwise we end up with a memory leak which slows down the browser. If you’ve worked with Angular, there is a pipe named <code>asyncPipe</code> which subscribes and unsubscribes automatically for you.</p>
<p>The way we unsubscribe is that we create a reference to each Observable that is subscribed by creating a variable to preserve its current state. And then, for each variable, we chain it with the <code>unsubscribe()</code> method. Remember that you can only unsubscribe after you’ve subscribed. It’s fairly simple but often forgotten.</p>
<p>Notice, if you unsubscribe here, <code>Observable_1</code> and <code>Observable_2</code> will output the data before it is unsubscribe because these are cold Observables (not time-dependent), while <code>Observable_3</code> and <code>Observable_4</code> will not output anything because these are hot Observables (time-dependent).</p>
<h3 id="heading-summary">Summary</h3>
<p>As mentioned above, the most challenging part of learning the observer pattern is the mindset. A mindset where we look at values differently, such as a sequence of data that emits over time. In this article, we’ve covered types of ways we can create an Observable, as well as how to subscribe and unsubscribe.</p>
<p>I recommend using the observer pattern because it provides everything that the promise pattern offers, and much more. It also provides a few great operators to prevent users from sending thousands of unnecessary requests to the backend.</p>
<p>One of them is <code>debonceTime</code> which gives the user enough time to write a complete word, and then send one request instead of a request for every character. You can, of course, achieve this with a simple promise, but that requires some lines of code.</p>
<p>I’ll cover more about reactive programming in the near future, stay tuned!</p>
<p>If you are interested to learn more about the web-ecosystem, here are few articles I’ve written to boost your web skills, enjoy :)</p>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/7-javascript-methods-that-will-boost-your-skills-in-less-than-8-minutes-4cc4c3dca03f">Boost your skills with these JavaScript methods</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-comparison-between-angular-and-react-and-their-core-languages-9de52f485a76">A comparison between Angular and React</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773">A practical guide to ES6 modules</a></li>
<li>[How to perform HTTP requests using the Fetch API](http://A practical ES6 guide on how to perform HTTP requests using the Fetch API)</li>
<li><a target="_blank" href="https://medium.freecodecamp.org/learn-these-core-javascript-concepts-in-just-a-few-minutes-f7a16f42c1b0?gi=6274e9c4d599">Important web concepts to learn</a></li>
</ul>
<blockquote>
<p><em>If you want to become a better web developer, start your own business, teach others, or improve your development skills, you can find me on Medium where I publish on a weekly basis. Or you can follow me on <a target="_blank" href="http://twitter.com/dleroari">Twitter</a>, where I post relevant web development tips and tricks.</em></p>
<p><em>P.S. If you enjoyed this article and want more like these, please clap ❤ and share with friends that may need it, it’s good karma.</em></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Go SUPER SAIYAN with RxJS Observables ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough I loved DragonBall Z as a kid, and still love it as an adult. Among the ludicrous number of transformations, the original Super Saiyan remains my favorite. Nothing quite like the original I’m also loving RxJS the more I level up... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/go-super-saiyan-with-rxjs-observables-d4681ae51930/</link>
                <guid isPermaLink="false">66d461913a8352b6c5a2ab30</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 17 Jul 2018 17:31:50 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*qE2wxzg_yiFOIN-Q" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p>I loved DragonBall Z as a kid, and still love it as an adult.</p>
<p>Among the ludicrous number of transformations, the original Super Saiyan remains my favorite.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*qE2wxzg_yiFOIN-Q" alt="0*qE2wxzg_yiFOIN-Q" width="333" height="500" loading="lazy"></p>
<blockquote>
<p>Nothing quite like the original</p>
</blockquote>
<p>I’m also loving RxJS the more I level up with it, so why not combine these two for the ultimate showdown?</p>
<h3 id="heading-lets-go-super-saiyan">Let’s Go Super Saiyan</h3>
<p>With four sprite sheets and a bit of HTML, CSS, and RxJS, we can recreate this legendary transformation!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qgex4ns9jPE_tpCy_OTfWA.gif" alt="1*qgex4ns9jPE_tpCy_OTfWA" width="600" height="563" loading="lazy"></p>
<p>This is what we’ll be making. Exciting, right?! ?</p>
<h3 id="heading-setup">Setup</h3>
<p>Everything’s on <a target="_blank" href="https://github.com/yazeedb/dbz-rxjs">my GitHub</a>.</p>
<pre><code>cd ./wherever-you-want
git clone [https:<span class="hljs-comment">//github.com/yazeedb/dbz-rxjs](https://github.com/yazeedb/dbz-rxjs)</span>
cd dbz-rxjs
</code></pre><p>Open <code>index.html</code> in your favorite browser, and the project in your favorite text editor, and you’re ready to go!</p>
<p>No <code>npm install</code>s today ?</p>
<p>And going forward, I’ll use the acronym “SSJ” instead of “Super Saiyan” for brevity.</p>
<h3 id="heading-first-day-of-training">First Day of Training</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*FpxB4WdbNMmldqZDnpVp1g.png" alt="1*FpxB4WdbNMmldqZDnpVp1g" width="860" height="666" loading="lazy"></p>
<p>You’ll notice that Goku’s already moving. Since we’re focusing on RxJS, we’ll just skim the project’s starting point.</p>
<p>Here’s the main HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"meter-container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hold any key to POWER UP!<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"meter"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sprite"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"base"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The bottom <code>div</code> has <code>class="base"</code>, which corresponds to this CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.base</span>,
<span class="hljs-selector-class">.ssj</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">120px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">250px</span>;
  <span class="hljs-attribute">animation</span>: stand <span class="hljs-number">0.8s</span> <span class="hljs-built_in">steps</span>(<span class="hljs-number">2</span>) infinite;
}

<span class="hljs-selector-class">.base</span> {
  <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">'img/goku-standing-sheet.png'</span>);
}
</code></pre>
<p>This sets Goku’s width, height, and standing animation.</p>
<p>If you look at his base/ssj sprite sheets, it’s two different positions and we’re switching between them every 0.8 seconds.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Cy1fArcSxNJwGDc98YMHEA.png" alt="1*Cy1fArcSxNJwGDc98YMHEA" width="250" height="227" loading="lazy"><img src="https://cdn-media-1.freecodecamp.org/images/1*mNVDs7NKfcfkA8l86IxOTA.png" alt="1*mNVDs7NKfcfkA8l86IxOTA" width="250" height="227" loading="lazy"></p>
<p>The switching’s handled towards the bottom of <code>style.css</code>:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> stand {
  <span class="hljs-selector-tag">from</span> {
    <span class="hljs-attribute">background-position</span>: <span class="hljs-number">0px</span>;
  }
  <span class="hljs-selector-tag">to</span> {
    <span class="hljs-attribute">background-position</span>: -<span class="hljs-number">255px</span>;
  }
}
</code></pre>
<p>Same thing for power up:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*sSTHMTvkazP0BaZPubo4kg.png" alt="1*sSTHMTvkazP0BaZPubo4kg" width="500" height="266" loading="lazy"><img src="https://cdn-media-1.freecodecamp.org/images/1*xkI3tsGLGRpVoH2RjaFK9w.png" alt="1*xkI3tsGLGRpVoH2RjaFK9w" width="500" height="267" loading="lazy"></p>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> powerup {
  <span class="hljs-selector-tag">from</span> {
    <span class="hljs-attribute">background-position</span>: <span class="hljs-number">0px</span>;
  }
  <span class="hljs-selector-tag">to</span> {
    <span class="hljs-attribute">background-position</span>: -<span class="hljs-number">513px</span>;
  }
}
</code></pre>
<p>We’ll cover the power up meter when we manipulate it.</p>
<h3 id="heading-mastering-the-dom-elements">Mastering the DOM Elements</h3>
<p><code>index.html</code> already includes <code>RxJS@6.2.1</code> via CDN, so you’re covered.</p>
<p>In <code>app.js</code>, let’s capture the DOM elements we’re interested in:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sprite = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#sprite'</span>);
<span class="hljs-keyword">const</span> meterContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#meter-container'</span>);
<span class="hljs-keyword">const</span> meter = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#meter'</span>);
</code></pre>
<p>I prefer to alias <code>document.querySelector</code> so using it doesn’t cause me wrist pain.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> $ = <span class="hljs-built_in">document</span>.querySelector.bind(<span class="hljs-built_in">document</span>);**
<span class="hljs-keyword">const</span> sprite = $(<span class="hljs-string">'#sprite'</span>);
<span class="hljs-keyword">const</span> meterContainer = $(<span class="hljs-string">'#meter-container'</span>);
<span class="hljs-keyword">const</span> meter = $(<span class="hljs-string">'#meter'</span>);
</code></pre>
<p>Next, we’ll create a <code>main</code> function and immediately call it.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ...</span>

<span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// do something</span>
};
main();
</code></pre>
<h3 id="heading-powering-up">Powering Up</h3>
<p>Here is <code>main</code>’s first code snippet:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { fromEvent } = rxjs;

  <span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
  <span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);
};
</code></pre>
<p>Goku should power up when a key is held down, and stop when that key is let go. We can use the <code>fromEvent</code> operator to create two observables:</p>
<ul>
<li><code>begin</code>: Notifies when the user presses a key <strong>down</strong>.</li>
<li><code>end</code>: Notifies whenever the user <strong>lets go</strong> of a key.</li>
</ul>
<p>Then we can <strong>subscribe</strong> to these emissions and act upon them. To get the power up animation, give <code>sprite</code> the <code>powerup</code> class name.</p>
<pre><code class="lang-js">begin.subscribe(<span class="hljs-function">() =&gt;</span> {
  sprite.classList.add(<span class="hljs-string">'powerup'</span>);
});
</code></pre>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*6-GLDooG9dTyGqNQ2XP0ww.png" alt="1*6-GLDooG9dTyGqNQ2XP0ww" width="856" height="618" loading="lazy"></p>
<p>It works, but pressing a key causes him to power up forever…</p>
<p>We must also subscribe to the <code>end</code> observable, so we know when the key has been let go.</p>
<pre><code class="lang-js">end.subscribe(<span class="hljs-function">() =&gt;</span> {
  sprite.classList.remove(<span class="hljs-string">'powerup'</span>);
});
</code></pre>
<p>Now he powers up and down at your command.</p>
<h3 id="heading-building-a-scouter">Building a Scouter</h3>
<p>Any DBZ fan has seen a scouter, the little eyewear used to track power levels (until like episode 20…).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*8H9CSUZbfDPxmdgR.png" alt="0*8H9CSUZbfDPxmdgR" width="816" height="506" loading="lazy"></p>
<blockquote>
<p>Obligatory &gt; 9000 joke</p>
</blockquote>
<p>As Saiyans power up, their power level grows. Inconceivable, right?</p>
<p>We need a way to track Goku’s power level as he ascends, and trigger the SSJ transformation after say, 100 points.</p>
<p>We can start his power off at 1, and increase it while the user holds a key down.</p>
<h4 id="heading-rxjs-operators">RxJS Operators</h4>
<p>Operators are where RxJS really shines. We can use pure functions to describe how data should transform through the stream.</p>
<p>When the user holds a key down, let’s transform those emissions into a number that increases over time.</p>
<h4 id="heading-scan">Scan</h4>
<p>The <a target="_blank" href="https://www.learnrxjs.io/operators/transformation/scan.html">scan operator</a> is perfect for this. It’s like <code>Array.reduce</code>, but it emits <strong>as it’s reducing</strong>.</p>
<p>For example, if you have an array of numbers:</p>
<pre><code class="lang-js">nums = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
</code></pre>
<p>And wish to add them up, <code>reduce</code> is a great choice.</p>
<pre><code class="lang-js">nums.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>);
<span class="hljs-comment">// 15</span>
</code></pre>
<p>What if you want to see each addition as it happens?</p>
<p>Enter <code>scan</code>. You can run this in our app’s console.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span> } = rxjs;
<span class="hljs-keyword">const</span> { scan } = rxjs.operators;

<span class="hljs-keyword">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>])
  .pipe(scan(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b, <span class="hljs-number">0</span>))
  .subscribe(<span class="hljs-built_in">console</span>.log);

<span class="hljs-comment">// 1 (0 + 1)</span>
<span class="hljs-comment">// 3 (1 + 2)</span>
<span class="hljs-comment">// 6 (3 + 3)</span>
<span class="hljs-comment">// 10 (6 + 4)</span>
<span class="hljs-comment">// 15 (10 + 5)</span>
</code></pre>
<p>See how the emissions increase over time? We can do that with Goku as he powers up!</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { fromEvent } = rxjs;
<span class="hljs-keyword">const</span> { scan, tap } = rxjs.operators;

<span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
<span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);

begin
  .pipe(
    scan(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level + <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
    tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log({ level });
    })
  )
  .subscribe(<span class="hljs-function">() =&gt;</span> {
    sprite.classList.add(<span class="hljs-string">'powerup'</span>);
  });
</code></pre>
<p>We start his level at <code>1</code> and increase it by 1 every time the <code>keydown</code> event fires.</p>
<p>And the <a target="_blank" href="https://www.learnrxjs.io/operators/utility/do.html">tap operator</a> operator lets us quickly log the value without disturbing the pipeline.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*CviOotpl-fpRm5qrI7INhQ.png" alt="1*CviOotpl-fpRm5qrI7INhQ" width="1600" height="859" loading="lazy"></p>
<blockquote>
<p>My power infinitely approaches MAXIMUM!</p>
</blockquote>
<h3 id="heading-going-super-saiyan">Going Super Saiyan</h3>
<p>We’ve trained hard, it’s time to transform.</p>
<p>The <code>scan</code> operator tracks Goku’s power level. Now we need to go SSJ when it emits 100.</p>
<p>I built a map of <code>levels: transformations</code>. You can put it right above <code>main</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> powerLevels = {
  <span class="hljs-number">100</span>: {
    <span class="hljs-attr">current</span>: <span class="hljs-string">'base'</span>,
    <span class="hljs-attr">next</span>: <span class="hljs-string">'ssj'</span>
  }
};

<span class="hljs-keyword">const</span> main = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// ...</span>
};
</code></pre>
<p>It’s overkill, but should simplify adding future transformations.</p>
<p>When the power level reaches a number in that <code>powerLevels</code> map, we’ll remove its <code>current</code> class from <code>sprite</code> and add the <code>next</code> class.</p>
<p>This lets us smoothly go from one transformation to the next.</p>
<p>Here’s the code.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { fromEvent } = rxjs;
<span class="hljs-keyword">const</span> { filter, map, scan, tap } = rxjs.operators;

<span class="hljs-keyword">const</span> begin = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keydown'</span>);
<span class="hljs-keyword">const</span> end = fromEvent(<span class="hljs-built_in">document</span>, <span class="hljs-string">'keyup'</span>);

begin
  .pipe(
    scan(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level + <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
    tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log({ level });
      sprite.classList.add(<span class="hljs-string">'powerup'</span>);
    }),
    map(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> powerLevels[level]),
    filter(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> level &amp;&amp; level.next)
  )
  .subscribe(<span class="hljs-function">(<span class="hljs-params">{ current, next }</span>) =&gt;</span> {
    sprite.classList.remove(current);
    sprite.classList.add(next);
  });
</code></pre>
<h4 id="heading-map-and-filter">Map and Filter</h4>
<p>Adding the <code>powerup</code> class now happens inside of <code>tap</code>, because it should always happen. The SSJ transformation however, <strong>shouldn’t</strong> always happen.</p>
<p>Using <code>map</code>, the latest power level becomes an entry in the <code>powerLevels</code> map. We use <code>filter</code> to check if the entry exists <strong>and</strong> has a <code>.next</code> property.</p>
<p>If it does, that means Goku can go even further beyond! Our <code>.subscribe</code> will swap <code>current</code> and <code>next</code> as class names on <code>sprite</code>.</p>
<p>The end result?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*q-ifHhrr8byMWPENjBpNyQ.gif" alt="1*q-ifHhrr8byMWPENjBpNyQ" width="600" height="411" loading="lazy"></p>
<h3 id="heading-power-meter">Power Meter</h3>
<p>You’re having as much fun as I am, right? Unfortunately, our user won’t.</p>
<p>They can’t see how high Goku’s power level is! They won’t know how to open the DevTools console. We must remedy this!</p>
<p>Let’s improve our UX by filling the power meter. You can put this above <code>main</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fillMeter = <span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> limit = <span class="hljs-number">100</span>;

  <span class="hljs-keyword">if</span> (level &gt;= limit) {
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">const</span> containerWidth = meterContainer.offsetWidth;
  <span class="hljs-keyword">const</span> newWidth = (level / limit) * containerWidth;

  meter.style.width = <span class="hljs-string">`<span class="hljs-subst">${newWidth}</span>px`</span>;
};
</code></pre>
<p>And call it inside <code>tap</code>.</p>
<pre><code class="lang-js">tap(<span class="hljs-function">(<span class="hljs-params">level</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log({ level });
  sprite.classList.add(<span class="hljs-string">'powerup'</span>);
  fillMeter(level);
});
</code></pre>
<p>And here we go:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qvr0L_5cmXzMI4g8sYtoyg.gif" alt="1*qvr0L_5cmXzMI4g8sYtoyg" width="600" height="318" loading="lazy"></p>
<h3 id="heading-going-even-further-beyond">Going Even Further Beyond</h3>
<p>Unlocking more transformations is just a matter of adding sprites, and updating our <code>powerLevels</code> map. If you’re interested, submit a PR on <a target="_blank" href="https://github.com/yazeedb/dbz-rxjs">the repo</a> and we’ll definitely talk.</p>
<p>Here’s the <a target="_blank" href="https://www.deviantart.com/bruguii/art/goku-fin-jus-268665173">original sprite sheet</a>. Enjoy!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A new way of building dynamic visualisations ]]>
                </title>
                <description>
                    <![CDATA[ By Sushrut Shivaswamy The Flux architecture gained popularity after Facebook adopted it. It’s a way of managing the state of React components so that the flow of the data through the app is unidirectional. The advantages of this approach are that the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-new-way-of-building-dynamic-visualisations-5c732091a3c1/</link>
                <guid isPermaLink="false">66c342dba1d481faeda49ae6</guid>
                
                    <category>
                        <![CDATA[ data visualization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 11 Apr 2018 14:26:08 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*pXitH0oMDdrvQRHjFsNM5g.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sushrut Shivaswamy</p>
<p>The Flux architecture gained popularity after Facebook adopted it. It’s a way of managing the state of React components so that the flow of the data through the app is unidirectional.</p>
<p>The advantages of this approach are that the app is comprised of few stateful components that passes state down to nested child components. A feature of React that really complements this approach to state management is that React allows us to write UI as a function of state. This means that, as state percolates down the app’s component hierarchy, components automatically change the view to reflect the changes in state.</p>
<p>JSX, a templating system used by React, allows for the creation of reusable single file components.</p>
<p>It also lends itself really well to creating a demarcation between the structure of the DOM and the behaviours associated with it.</p>
<ul>
<li>JSX gives a clean view of the DOM structure that is more intuitive than the several lines of JavaScript required to create the same DOM structure.</li>
<li>The behaviours associated with the DOM structure — eventHandlers like onClick, onHover — are handled as member functions of the component.</li>
<li>Any changes to the DOM structure require the user to call <strong>setState to change the state of the component instead of directly mutating the DOM</strong>. This makes it easier to debug the application, and it also ensures that the application is always in a defined state.</li>
</ul>
<p>As the complexity of the app grew, however, the Flux approach also began to show its limitations.</p>
<p>Few stateful components passing state down to child components seem fine for small apps. But, as the complexity of the component hierarchy increases, stateful components have to share state with each other.</p>
<p>While it is possible to share state across different components/classes in JavaScript through common variables or, preferably, the Observer pattern, as the number of components increases it becomes harder to maintain the application.</p>
<p>The simplicity of components reacting to changes in state is muddled with the complexities of object-oriented design.</p>
<h3 id="heading-charts-why-are-they-hard-to-make"><strong>Charts — why are they hard to make?</strong></h3>
<p>The advances that web apps have benefited from have not changed the way that charting libraries are made. A chart is also a presentational component, and can technically be termed as UI. A chart is also composed of DOM elements that control its visual appearance.</p>
<p>However, charts differ in one key aspect: developers don’t treat SVG as DOM. Technically, the <code>&lt;s</code>vg&gt; tag is not even an HTMLElement like other DOM elements, and sits in a separate namespace. SVG is only known for its ability to scale to any viewport size and maintain the resolution of the image at a constant level. That’s the extent to which most developers know about it.</p>
<p>Also the tags used to create an SVG image like <code>&lt;poi</code>nt<code>&gt;, &amp;l</code>t;rect <code>/&gt;, and</code>  sound very “math like.” This makes developers shy away from how SVG structures actually work.</p>
<p>Even those involved with applications that make heavy use of SVG are usually unaware of its inner workings. They utilise other libraries like <a target="_blank" href="http://snapsvg.io/">snap</a> or d3 to avoid the hassle of understanding what goes on under the hood.</p>
<p>Having avoided the underlying complexity of the SVG tag, it feels easy to model complex SVG constructs.</p>
<h4 id="heading-geometry">Geometry</h4>
<p>Consider a bar chart, for example.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*TODhoVI3-CTxOhWU.png" alt="Image" width="481" height="289" loading="lazy">
<em>A nice bar chart.</em></p>
<p>We traditionally adopt a cookie cutter approach and split a chart into parts:</p>
<ul>
<li>x-axis</li>
<li>y-axis</li>
<li>bars</li>
</ul>
<p>A seasoned developer would notice that the word axis was written twice in the above list. So lets create an abstraction layer called <code>Axis</code> that subclasses can inherit from.</p>
<p>To render the bars, we can create a separate class called <code>Bar</code> that utilises the <strong>scale provided by the</strong> <code>axis</code> <strong>class</strong>. As charts come in various shapes, it makes more sense to have an abstraction layer called <code>Geometry</code> <strong>that other classes can inherit from, namely</strong> <code>Bar</code>, <code>Point</code>, <code>Line</code>, and <code>Area</code>. As more complex charts are made, several new geometry types can be added to render different kinds of charts.</p>
<p>Following the above methodology, a chart comprises three or more stateful components that utilise each others’ properties to render a meaningful chart.</p>
<p>To update or enhance the chart, a developer is expected to <strong>know the state to mutate in each of these components</strong>. Since state is scattered across various components, even simple changes take a lot of time for new developers. <strong>The ordering of the state changes also becomes relevant.</strong></p>
<p>In the above example, the geometry utilises the scale of the axes. For the chart to be resized, the range of each axis has to be updated <strong>before</strong> updating the <code>Geometry</code>.</p>
<p>Not following this ordering will lead to visual artefacts — because the geometry would be distorted due to an invalid scale. At worst, failure to carry out this <strong>ordered sequence of operations</strong> could leave the chart in an undefined state.</p>
<p>Having cross-connectivity between charts further compounds this problem. The orchestration of state changes spans multiple charts/interacting components.</p>
<p>Having so many interacting components with directed relationships can also lead to cyclic dependencies between components.</p>
<p>This was a problem that plagued UI development frameworks as well until developing web applications with a single source of truth became the standard. The most influential library in directing the shift to single source of truth webapps was Redux.</p>
<p><strong>Note</strong>: The next section explains how using Redux makes web app development easier. Feel free to skip it if you already know about Redux.</p>
<h3 id="heading-redux"><strong>Redux</strong></h3>
<p><a target="_blank" href="https://redux.js.org/">Redux</a> is a library developed by Dan Abhramov. It helps ease the burden of developers by providing an easy way to maintain the state of an application.</p>
<p>Redux introduced the concept of a state store that acted as the single source of truth for the entire application. Instead of components directly mutating the state, each component would dispatch an action that would commit a change to the unified state store.</p>
<p>Each action was identified by a <strong>unique enum that would be logged every time a change was committed to the state store.</strong> This made it easy to track how the state store was being mutated.</p>
<p>Once a change was committed to the state store, the new state would percolate down the component hierarchy. Components would re-render or ignore the change depending on whether the part of the state that changed was relevant to them. Components could no longer mutate the state in isolation. It had to be at a global level.</p>
<p><strong>The main purpose is to isolate state management from side effects like rendering and fetching data from the server. Always leave the application in a defined state.</strong></p>
<p>This lays the foundation for a deterministic view render. Given a sequence of state changes, you will always end up with the same rendered view.</p>
<p>This level of deterministic view rendering is especially helpful for offline applications. Here, the sequence of state mutations that happen while user is offline can be stored and replayed when connectivity is re-established to get back the same view.</p>
<p>The success of of the React-Redux model spawned a number of other libraries like <a target="_blank" href="https://vuejs.org/">Vue</a> and <a target="_blank" href="https://cycle.js.org/">Cycle</a>, as well as several other implementations of the state store like <a target="_blank" href="https://mobx.js.org/index.html">MobX</a> and <a target="_blank" href="https://vuex.vuejs.org/en/intro.html">Vuex</a>.</p>
<h3 id="heading-a-closer-look-at-svg"><strong>A closer look at SVG</strong></h3>
<p>SVG stands for scalable vector graphics. The <code>svg</code> tag can optionally house various kinds of geometry, which expose a number of DOM attributes.</p>
<p><strong>Circle</strong>: <code>&lt;circle</code> /&gt;</p>
<p>Attributes:</p>
<ul>
<li><strong>cx</strong>: x offset of circle in viewport</li>
<li><strong>cy</strong>: y offset of circle in viewport</li>
<li><strong>r</strong> : radius of circle</li>
</ul>
<p><strong>Polyline</strong>: <code>&lt;polyline</code> /&gt;</p>
<p>Attributes:</p>
<ul>
<li><strong>points:</strong> array of points (x, y) through which a <strong>line</strong> is drawn.</li>
</ul>
<p><strong>Polygon</strong>: <code>&lt;polygon</code> /&gt;</p>
<p>Attributes:</p>
<ul>
<li><strong>points</strong>: array of points (x, y) to construct a polygon.</li>
</ul>
<p><strong>Text</strong>: <code>&lt;text</code> /&gt;</p>
<p>Attributes:</p>
<ul>
<li><strong>x</strong>: x offset of text in viewport</li>
<li><strong>y</strong>: y offset of text in viewport</li>
<li><strong>innerText</strong>: The text to show.</li>
</ul>
<p>Many more geometry types are available in the SVG standard, but for the purposes of charts, the above will suffice. These geometric elements can also be styled with normal CSS.</p>
<h3 id="heading-finding-a-bridge"><strong>Finding a bridge</strong></h3>
<p>These are the guiding principles behind modern web application development and development of charting libraries. Let’s try to isolate where developing charting libraries differs from web applications:</p>
<ul>
<li><strong>web apps</strong> are composed of DOM nodes. <strong>Charts</strong> are composed of SVG geometries.</li>
<li><strong>web apps</strong> can be broken down into reusable sections of DOM that can be modelled as components. <strong>Charts</strong> aren’t modelled as reusable set of geometries.</li>
<li><strong>web app</strong> frameworks are always coupled with a templating engine so that DOM structure can be modelled in markup and the behaviours can be separated from it and written in JavaScript. <strong>Charts</strong> have no such framework available.</li>
<li><strong>web app</strong> frameworks allow for a state store to be incorporated through the use of a plugin. <strong>Charts</strong> are usually modelled as stateful components.</li>
</ul>
<h3 id="heading-remodelling-chart-complexity"><strong>Remodelling chart complexity</strong></h3>
<p>A chart is a visual tool that showcases variation across fields in the data using geometry.</p>
<p>So how does that work?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*sIbDX48h24oTItLL.png" alt="Image" width="800" height="568" loading="lazy">
<em>A nice scatter plot</em></p>
<p>Looking at the chart above, what do we see? Circles offset in the viewport based on fields present in the data.</p>
<p>What else?</p>
<ul>
<li>Ticks offset along the bottom based on a field in the data.</li>
<li>Text labels offset along the bottom based on a field in the data.</li>
<li>Same as above along the left side of the chart.</li>
</ul>
<p>Let’s break it down to the level of geometries.</p>
<p>How do we render the circles in the scatterplot?</p>
<p><code>&lt;circle cx=”horsepowerScale()” cy=”milesPerGallonScale()” cr=”const”</code> /&gt;</p>
<p>What about the axes? X-Axes: Text + Ticks</p>
<p><code>&lt;text x=”horsepowerScale()” y=”0”&gt;{{ text value }}&amp;</code>lt;/text&gt;</p>
<p><code>&lt;tick x=”horsepwerScale()” y=”0”</code> /&gt;</p>
<p>There is a similar SVG structure for the y-axis, except that the scale function changes and the x, y fields are inverted.</p>
<p>The common theme above is that the <strong>chart is viewed as a meaningful arrangement of geometry:</strong></p>
<ul>
<li>each geometry in the SVG namespace exposes visual attributes</li>
<li>the value of these attributes is bound to a calculated value</li>
<li>the calculated value depends on the scale</li>
<li>the scale depends on a field in the data and the range</li>
</ul>
<h4 id="heading-what-is-a-scale"><strong><em>What is a scale?</em></strong></h4>
<p>A scale is a function that maps data to a position in the viewport.</p>
<p>What is the input to scale?</p>
<ul>
<li>the domain of the field</li>
<li>the length of the viewport to map to</li>
</ul>
<p>Let <strong>R</strong> be the length of viewport and <strong>D</strong> be the domain of the data.</p>
<ul>
<li>Then we can define a scaling function <strong>S</strong> as:</li>
<li><strong><em>S = f(D, R) + b</em></strong></li>
</ul>
<p>where <strong>b</strong> is a constant.</p>
<h4 id="heading-how-many-scales-does-a-chart-need-to-have"><strong><em>How many scales does a chart need to have?</em></strong></h4>
<p>If you’re thinking two, then you’re wrong.</p>
<p>Scale doesn’t exist only along x- and y-axes. The axes themselves are only present in a chart as <strong>visual anchors</strong> so that <strong>users can line up data variations along multiple dimensions.</strong></p>
<p>The axis is just geometry that is rendered using a scale.</p>
<h4 id="heading-how-many-dimensions-are-there"><strong><em>How many dimensions are there?</em></strong></h4>
<p>It’s not two. The viewport is two-dimensional but that has nothing to do with the dimensionality of the chart. The dimensionality of a chart is defined by the number of scaling functions used.</p>
<p>The overarching concept comprises of two simple terms: <strong>Geometry</strong> and <strong>Scale</strong>.</p>
<p>Each geometry exposes visual attributes that control its appearance.</p>
<p>The value of these attributes can be hooked up to scaling functions. The scaling function is tied to a particular field in the data.</p>
<p><strong>This lends itself to the idea that every visual attribute in a chart can only be tied to one field in the data table.</strong></p>
<p>Given this decomposition of charts we can model the scatter plot above as follows:</p>
<p>The field <code>Horsepower</code> is used to create a scaling function called <code>horsepowerScale()</code>.</p>
<p>The field <code>Acceleration</code> is used to create a scaling function called <code>accelerationScale()</code>.</p>
<p>Since we are not varying the size of the circles, only two scaling functions are required.</p>
<p>Any circle <strong>i</strong> in the scatterplot can be represented as</p>
<p><code>&lt;circle cx="horsepowerScale(ti)" cy="accelerationScale(ti)" cr="5"</code> /&gt;</p>
<p>where <code>ti</code> is the <code>i</code>th tuple in the Datatable.</p>
<p>Given that only two scaling functions were used, the dimensionality of the above chart becomes two.</p>
<p><strong>If we also modulated the size of each circle, using a scaling function tied to another field, then the dimensionality would be three.</strong></p>
<p>Doing so would result in what is known as a “bubble chart”.</p>
<h4 id="heading-grammar-of-graphics">Grammar of Graphics</h4>
<p>This is similar to the <a target="_blank" href="https://codewords.recurse.com/issues/six/telling-stories-with-data-using-the-grammar-of-graphics">Grammar of Graphics (GOG)</a> approach, where every chart is defined by a mark (geometry) and the visual encodings used by the mark.</p>
<p>In a GOG approach the scatterplot would be represented as:</p>
<pre><code>{
</code></pre><pre><code>    mark: <span class="hljs-string">'circle'</span>,
</code></pre><pre><code>    encoding: {
</code></pre><pre><code>        x: <span class="hljs-string">'horsepower'</span>,
</code></pre><pre><code>        y: <span class="hljs-string">'acceleration'</span>
</code></pre><pre><code>    }
</code></pre><pre><code>}
</code></pre><p><strong>Notice that there is a one-to-one mapping between the encoding of a GOG geometry and the visual attributes exposed by the geometry in SVG</strong>.</p>
<p>The axis can also be rendered similarly:</p>
<ul>
<li>The x-axis is a tick geometry with its x-offset attribute tied to <code>horsepowerScale()</code> and its y-offset set to 0.</li>
<li>The y-axis is a tick geometry with its y-offset attribute tied to <code>accelerationScale()</code> and its x-offset set to 0.</li>
</ul>
<p>To render the scatterplot with all its elements, the following snippet of code would suffice:</p>
<p>Decomposition of charts into an association between visual attributes and a scaling function allows us to view a chart as a web app.</p>
<p><strong>Web Application frameworks model UI as a function of state.</strong></p>
<p><strong>Charts Frameworks should model geometry as a function of scale.</strong></p>
<p>So the idea that makes web applications easy to develop can easily be extended to creating charts:</p>
<ul>
<li>Initially, tabular data is supplied as input.</li>
<li>For every field in the Data array, a scaling function is created. The scaling function selectively recomputes values when a field in the column is tied to changes. The same scaling function is percolated throughout the application.</li>
<li>Every geometry is modelled as a component that exposes visual attributes.</li>
<li>The value of these visual attributes is tied to a scaling function that reacts to changes in data.</li>
<li>The collections of geometry can be represented in markup using a templating engine of choice like hyperHTML, mustache, or handlebars. Ideally, the templating engine should be introduced as a plugin so that we can avoid writing bindings for different libraries like React and Angular.</li>
<li>The state store that selectively computes scales should also be introduced as a plugin.</li>
</ul>
<p>Let’s see what putting a chart together using the above principles would look like:</p>
<p>We are using React as a templating engine and Redux as the state store in the above example.</p>
<p>The above approach is just a rough implementation of what a framework that can model charts as webapps would would like like.</p>
<p><strong>Notice the separation of the templating engine and state store from the actual rendering logic.</strong></p>
<h3 id="heading-final-points">Final points</h3>
<p>Ideally, geometries/charts that we create should be available as components in the framework of the user’s choice along with their state store. If it seems unthinkable that something like this could even be done, stay calm. It’s been done before.</p>
<p><a target="_blank" href="http://skatejs.netlify.com/">SkateJS</a> is a compiler that creates web components but allows user to switch internal rendering engines.</p>
<p><strong>Users can choose between React, Preact, lit-html or extend the Renderer interface to write their own.</strong> The default renderer just mutates the DOM directly.</p>
<p>We can be even more ambitious with what we choose once we have synchronous rendering coupled with state management.</p>
<p>Imagine a <code>TickProvider</code> component that allows for rendering only small clusters of geometry in a given animation frame as well as allowing us to identify bottlenecks in our rendering pipeline.</p>
<p>Given that a chart is meaningful arrangement of geometry, it follows that meaningful clusters of geometry should render together.</p>
<p>In the scatter plot example, for every group of circles that render, the corresponding sections of the x/y axis geometry should also render simultaneously.</p>
<p>If we break the rendering into chunks, where each chunk consists of one meaningful cluster of geometry as modelled above, we can support beautiful transitions that add to the visual appeal of the chart.</p>
<p>Another advantage of a <code>TickProvider</code> is that we can profile and ensure that each cluster of geometry renders completely in the time allotted per tick. This will help avoid freezing of the UI when the geometry count to be rendered is very large. Instead of running a render loop over the entire geometry collection, we could batch the render calls in sync with the animation frames.</p>
<p>We can also break down the calculation of visual attribute values.</p>
<p>Consider a data table that has <strong>N</strong> fields being used to render dashboards with the above approach.</p>
<p>Since we are using a centralised state store, we can calculate the values of the <strong>N</strong> scaling function and memorize them. They only need to be re-calculated when the associated data table field changes.</p>
<p>Also, consider the equation below that computes the value of <strong>m</strong> visual attributes based on the scaling functions.</p>
<p>The 0th value for a visual attribute <strong>V</strong>, that is bound to field 0 of <strong>N</strong>, can be calculated as follows:</p>
<p>V(0) = S(d0, R) + b0</p>
<ul>
<li>where d0 is the 0th data tuple from the data table</li>
<li>R is the range supplied as a prop to the component</li>
<li>b0 is constant</li>
</ul>
<p>If we write a series of such equations together we see this:</p>
<p>V(0) = S(d0, R) + b0</p>
<p>V(1) = S(d1, R) + b1</p>
<p>V(2) = S(d2, R) + b2</p>
<p>..</p>
<p>V(m) = S(dm, R) + bm</p>
<p>The scaling function itself can be expressed as a linear equation. We have a set of linear equations that can be batch computed to calculate the value for visual attributes.</p>
<p>How so?</p>
<p>The above arrangement looks suspiciously like a matrix.</p>
<p><strong>Computations in the browser are slow, but matrix computations can be sped up by leveraging GPU acceleration.</strong></p>
<p>Modelling the chart as geometry as a function of scale could therefore help us render charts much faster, as well handle larger volumes of data with a fast first render.</p>
<p>Data Visualisation is something that help us glean insights from large quantities of data. The impact that it has on decision making is slowly going up with multiple organisations looking to make data driven decisions.</p>
<p>Safe to say, we need a more robust, accessible and maintainable way of developing visualisations.</p>
<p><strong>What do you think?</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to run tests in RxSwift ]]>
                </title>
                <description>
                    <![CDATA[ By Navdeep Singh RxTest and RxBlocking are part of the RxSwift repository. They are made available via separate pods, however, and so require separate imports. RxTest provides useful additions for testing Rx code. It includes TestScheduler, which is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/testing-in-rxswift-2b6eeaeaf432/</link>
                <guid isPermaLink="false">66c360719539e75f2cc24a27</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iOS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxSwift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 19 Mar 2018 04:15:05 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*ASJBAG5pLUIdEpVU4_RM2A.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Navdeep Singh</p>
<p><strong>RxTest</strong> and <strong>RxBlocking</strong> are part of the RxSwift repository. They are made available via separate pods, however, and so require separate imports.</p>
<p><strong>RxTest</strong> provides useful additions for testing Rx code. It includes <strong>TestScheduler</strong>, which is a virtual time scheduler, and provides methods for adding events at precise time intervals.</p>
<p><strong>RxBlocking</strong>, on the other hand, enables you to convert a regular Observable sequence to a blocking observable, which blocks the thread it’s running on until the observable sequence completes or a specified timeout is reached. This makes testing asynchronous operations much easier.</p>
<p>Let’s look at each one now.</p>
<h3 id="heading-rxtest">RxTest</h3>
<p>As described above, <strong>RxTest</strong> is part of the same repository as <strong>RxSwift.</strong> There is one more thing to know about <strong>RxTest</strong> before we dive into some RxTesting: RxTest exposes two types of Observables for testing purposes.</p>
<ul>
<li>HotObservables</li>
<li>ColdObservables</li>
</ul>
<p>HotObservables replay events at specified times using a test scheduler, regardless of whether there are any subscribers.</p>
<p>ColdObservables work more like regular Observables, replaying their elements to their new subscribers upon subscription.</p>
<h3 id="heading-rxblocking">RxBlocking</h3>
<p>If you are familiar with expectations in <strong>XCTest</strong>, you will know that it’s another way to test asynchronous operations. Using RxBlocking just happens to be way easier. Let’s start with a small implementation so we can see how to take advantage of this library while testing asynchronous operations.</p>
<h3 id="heading-testing-with-rxblocking">Testing with RxBlocking</h3>
<p>We will start a new test and create an Observable of 10, 20, and 30, as follows:</p>
<pre><code>func testBlocking(){        <span class="hljs-keyword">let</span> observableToTest = Observable.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>)    }
</code></pre><p>Now we will define the result as equal to calling toBlocking() on the observable we created:</p>
<pre><code><span class="hljs-keyword">let</span> result = observableToTest.toBlocking()
</code></pre><p><strong>toBlocking()</strong> returns a blocking Observable to a straight array, as you can see here:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1F4TF7RZ2FlBgcynP9tWUi9UqQBtLCCy6YSg" alt="Image" width="488" height="187" loading="lazy"></p>
<p>We will need to use the first method if we want to discover which is a throwing method. So we will wrap it in a do catch statement, and then we will add an <strong>AssertEquals</strong> statement if it is successful, as follows:</p>
<pre><code>func testBlocking(){        <span class="hljs-keyword">let</span> observableToTest = Observable.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>)        <span class="hljs-keyword">do</span>{            <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">try</span> observableToTest.toBlocking().first()            XCTAssertEqual(result, <span class="hljs-number">10</span>)        } <span class="hljs-keyword">catch</span> {        }    }
</code></pre><p>Alternatively, an Assert fails if it’s not this:</p>
<pre><code><span class="hljs-keyword">do</span>{            <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">try</span> observableToTest.toBlocking().first()            XCTAssertEqual(result, <span class="hljs-number">10</span>)        } <span class="hljs-keyword">catch</span> {            XCTFail(error.localizedDescription)        }
</code></pre><p>That’s it! Let’s run the test, and you will see that the test passes. We can simplify this test with just two lines of code by forcing the try.</p>
<p>Again, this is more acceptable on test than production code. We will comment out the do catch statement and then write the assert equals in a single line, as follows:</p>
<pre><code>XCTAssertEqual(<span class="hljs-keyword">try</span>! observableToTest.toBlocking().first(), <span class="hljs-number">10</span>)
</code></pre><p>Rerun the test, and you will see that the test passes once again. The overall code with comments looks like this:</p>
<pre><code>func testBlocking(){        <span class="hljs-keyword">let</span> observableToTest = Observable.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>)<span class="hljs-comment">//        do{//            let result = try observableToTest.toBlocking().first()//            XCTAssertEqual(result, 10)//        } catch {//            XCTFail(error.localizedDescription)//        }        XCTAssertEqual(try! observableToTest.toBlocking().first(), 10)    }</span>
</code></pre><p><strong>How’s that for succinct?</strong> Truth be told, that Observable sequence would actually be synchronous already if we printed emitted elements in a subscription to it followed by a marker. The marker will be printed after the subscription’s completed event.</p>
<p>To test an actual asynchronous operation, we will write one more test. This time, we will use a concurrent scheduler on a background thread, as follows:</p>
<pre><code>func testAsynchronousToArry(){        <span class="hljs-keyword">let</span> scheduler = ConcurrentDispatchQueueScheduler(qos: .background)    }
</code></pre><p>Now, we will create an Observable of the simple sequence of integers. We will use map to double each value, as follows:</p>
<pre><code><span class="hljs-keyword">let</span> intObservbale = Observable.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>)            .map{ $<span class="hljs-number">0</span> * <span class="hljs-number">2</span> }
</code></pre><p>Then, we will subscribe on the scheduler:</p>
<pre><code><span class="hljs-keyword">let</span> intObservbale = Observable.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>)            .map{ $<span class="hljs-number">0</span> * <span class="hljs-number">2</span> }            .subscribeOn(scheduler)
</code></pre><p>Now we will write a do catch statement that is similar to the last test and calls toBlocking on the Observable, which should be observed on the main scheduler, as follows:</p>
<pre><code><span class="hljs-keyword">do</span>{   <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">try</span> intObservbale.observeOn(MainScheduler.instance).toBlocking().toArray()   } <span class="hljs-keyword">catch</span> {   }
</code></pre><p>Then, we will add the same assertions as the previous example:</p>
<pre><code><span class="hljs-keyword">do</span>{   <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">try</span> intObservbale.observeOn(MainScheduler.instance).toBlocking().toArray()            XCTAssertEqual(result, [<span class="hljs-number">20</span>, <span class="hljs-number">40</span>, <span class="hljs-number">60</span>])        } <span class="hljs-keyword">catch</span> {            XCTFail(error.localizedDescription)        }
</code></pre><p>Now we will run the test, and you will note that it passes with the green check mark in the gutter.</p>
<p>Note that the marker is printed before the emitted elements in the console, as shown:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/699d2sSCtcHgNblX68UK9VKzUBF-f1aTW8r0" alt="Image" width="633" height="95" loading="lazy"></p>
<p>This is because these operations were executed asynchronously.</p>
<p>For other updates you can follow me on Twitter on my twitter handle @NavRudraSambyal</p>
<p>To work with examples of hot and cold observables, you can find the link to my book <a target="_blank" href="https://www.amazon.com/Reactive-Programming-Swift-easy-maintain-ebook/dp/B078MHNSL1/ref=asap_bc?ie=UTF8">Reactive programming in Swift 4</a></p>
<p>Thanks for reading, please share it if you found it useful :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Phone Number Authentication with Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By Jinwoo Choi Phone Number Authentication Many mobile applications require membership. Most of them provide user authentication. This is because you need to check whether the user in use is the same as the subscriber when preventing duplicate subscr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/phone-number-authentication-with-reactive-programming-6e89a2a651d2/</link>
                <guid isPermaLink="false">66c35c91b8711219e1e72dc1</guid>
                
                    <category>
                        <![CDATA[ Apps ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 14 Mar 2018 11:28:11 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*PyLjEXgdDViFQJarHsi7lw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jinwoo Choi</p>
<h3 id="heading-phone-number-authentication">Phone Number Authentication</h3>
<p>Many mobile applications require membership. Most of them provide user authentication. This is because you need to check whether the user in use is the same as the subscriber when preventing duplicate subscriptions or changing passwords.</p>
<p>Most mobile applications use a phone number to authenticate users, since they run on mobile phones. Phone number authentication consists of several steps, which means state management is required. You must also change the UI accordingly. This also requires asynchronous event handling, such as requesting a verification code and passing user-entered code to the server.</p>
<p>Therefore, phone number authentication can be a very good topic for writing about development skills. In this article, I will first implement phone number authentication in the usual way. Then I will introduce Reactive Programming.</p>
<h3 id="heading-ui-flow-of-phone-number-authentication">UI flow of Phone Number Authentication</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YOEtnAFE5I6BatRw0swIqA.png" alt="Image" width="800" height="355" loading="lazy"></p>
<p>During the authentication process, you must change the user interface for each step. For example, the related Button should be activated depending on the presence of the input value. And the UI component should be displayed or hidden according to the authentication step. Also, the Tip should be displayed to suit the situation. This article focuses on the following three cases.</p>
<ul>
<li>Activate [Request verification code] Button when entering a phone number (Step 1)</li>
<li>Hide [Verification code] TextField and [Authenticate] Button when authentication is successful (Step 4)</li>
<li>Display related message (tip) when authentication is completed or failed (step 5)</li>
</ul>
<h3 id="heading-basic-structure">Basic structure</h3>
<p>First, we’ll define an Enum with five states for each authentication step as follows. We declare it as a property of the Swift class and it has a didSet observer. We’ll add the code that changes the UI according to the authentication step here.</p>
<pre><code>enum PhoneNumberVerifyStep {    <span class="hljs-keyword">case</span> inputPhoneNumber, inputVerifyNumber, verifying, succeed, failed}
</code></pre><p>UI components consist of two TextFields, two Buttons, and one Label as follows. All are created through InterfaceBuilder and connected to IBOutlet. As mentioned earlier, we’ve declare a class property for storing the authentication step named verifyStep, and we’ve added a didSet observer to handle UI changes.</p>
<h3 id="heading-change-ui-based-on-authentication-step">Change UI based on authentication step</h3>
<p>Here is the part that actually changes the UI. Set the isHidden property of the [Verification code] TextField and the [Authentication] Button according to the changed value of <strong>verifyStep</strong>, and change the text of the [Tip] Label.</p>
<p>After calling the Restful API from the [Authentication] Button’s action method, set the appropriate value for <strong>verifyStep</strong> according to the response. <strong>Since we used the didSet observer for changing the UI, there is an advantage to separating the UI code and data processing code.</strong></p>
<p>Whether the [Request verification code] Button is active depends on the real-time input value of the [Phone number] TextField, not the authentication step. Therefore, we add an action handler to <strong>phoneNumberTextField</strong> that sets the <strong>isEnabled</strong> of <strong>requestVerifyNumberButton</strong> according to the input value.</p>
<p>In this way, we’ve implemented the UI changes according to the phone number authentication step in the usual way. Now, after looking at some of the disadvantages of the old method, I will modify the example and do it in the Reactive way, which is the subject of this article.</p>
<p>First, <strong>the internal implementation of the didSet observer in verifyStep may be too large</strong>. And the code that sets up one View can exist across multiple cases in the Switch statement. Many parts need to be modified to remove a specific View or add a new View. Above all, it is hard to read if the code gets longer.</p>
<p>Changing the enable property of the Button according to the input value of TextField can be inconvenient: <strong>the text input event handler should be added continuously if the number of the TextField and Button that need similar processing is increased</strong>. If you need to add real-time validation logic to the input value in the TextField, the inside of the event handler can be complicated.</p>
<p>Now, let’s improve these shortcomings by applying Reactive Programming. Here we use the open source library <a target="_blank" href="https://github.com/ReactiveCocoa/ReactiveCocoa"><strong>ReactiveCocoa</strong></a>.</p>
<h3 id="heading-reactive-programming">Reactive Programming</h3>
<p>Reactive Programming is the process of constructing a program using a function that responds to the stream of data in a time-sequential manner. The basic concept is not new — consider the following use cases. For example, the Button’s click event is basically observing asynchronous events and subscribing through callbacks. In addition, Cocoa has already provided a number of tools to implement Observer Patterns for data as well as UI Events.</p>
<blockquote>
<p><a target="_blank" href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754#reactive-programming-is-programming-with-asynchronous-data-streams"><strong>Reactive programming is programming with asynchronous data streams.</strong></a></p>
<p>In a way, this isn’t anything new. Event buses or your typical click events are really an asynchronous event stream, on which you can observe and do some side effects. Reactive is that idea on steroids. You are able to create data streams of anything, not just from click and hover events</p>
</blockquote>
<p>However, Reactive Programming goes beyond just using the tools mentioned above, to the use of Observer Pattern as the core of programming.</p>
<p>It abstracts the flow of all types of primitive data handled by the UI — Control Action, Notification, Delegate, and KVO, which are basic tools provided by Cocoa, as a stream. It also provides functions to process and filter the data flowing through it, which can be easily used in various areas.</p>
<p>In other words, reactive programming is a <strong>more integrated and easier way to handle chain reaction processing (and programming based on it) due to state changes</strong> than traditional methods.</p>
<p>Basically, its function-oriented coding aims to perform a single role in a function connected to a stream. This avoids complicated stateful programs such as the verifyStep didSet observer of the previous example, and makes it easy to handle error handling and concurrency control of asynchronous processing. See <a target="_blank" href="http://reactivex.io/">ReactiveX.io</a> for more information.</p>
<h3 id="heading-implement-reactive-programming">Implement Reactive Programming</h3>
<p>Ok, it’s time to stop explaining long, boring theories. From now on, let’s improve the phone number authentication example using the open source library ReactiveCocoa.</p>
<p>First of all, we remove the code that changes the UI according to the authentication step of the previous example, and only the basic skeleton of ViewController is left. We also remove the didSet observer for verifyStep, the editing action handler for the TextField, and the action method for the [Authenticate] Button.</p>
<p>Implement the following code using ReactiveCocoa based on the skeleton. The entire code was attached because it was not long. Let’s first look at <strong>Property</strong> of ReactiveSwift, and let’s look at the implementation by dividing the authentication step process into three types as shown in the previous example.</p>
<h3 id="heading-mutable-property-of-reactiveswift">(Mutable) Property of ReactiveSwift</h3>
<p>Property is a class provided by ReactiveSwift, which is the base of ReactiveCocoa. It provides the ability to handle data as a stream. For example, in the example code, <strong>verifyStep</strong> is a Holder for PhoneNumberVerifyStep type data. It can generate a signal when changing the value, or change the value in response to other data changes.</p>
<pre><code><span class="hljs-keyword">var</span> verifyStep = MutableProperty&lt;PhoneNumberVerifyStep(...)
</code></pre><p>That is, when the value of Property (verifyStep) changes, the UI can be changed. Or when the input value of TextField is changed, the value of variable (verifyStep) can be changed with it. <strong>The didSet observer of the Swift class property provides similar functionality.</strong> However, MutableProperty has the advantage of being able to <strong>change or filter the values ​​passed through the stream</strong> as described above, and to <strong>connect with the UI change code much more concisely.</strong></p>
<h3 id="heading-ui-binding-and-lt-operator-of-reactivecocoa">UI Binding and &lt;~ operator of ReactiveCocoa</h3>
<p>ReactiveCocoa provides Binding to easily handle UI changes due to Property changes. The UI component can create a BindingTarget for each of its configurable attributes. And this has a form of Command Pattern.</p>
<p>For example, ReactiveCocoa provides BindingTarget, which is the command that changes UILabel’s text. The BindingTarget is executed when a Signal is generated from the stream and sets the received value to the text of the UILabel.</p>
<p>The &lt;~ operator is provided to make it easier to connect the Signal to the BindingTarget. For example, the code below sets the value (input value) passed from the Signal (that is generated when the value of textField changes) to the text of the label.</p>
<pre><code>label.reactive.text &lt;~ textField.reactive.continuousTextValues
</code></pre><p><strong>label.reactive.text</strong> returns a <strong>BindingTarget</strong> instance that changes the text, and <strong>textField.reactive.continuousTextValues</strong> ​​returns a <strong>Signal</strong> instance that raises an event when the input value changes. The <strong>BindingTarget</strong> instance and the <strong>Signal</strong> instance are bound through <strong>&amp;l</strong>t;~, so when the input value of the textField changes, the text of the label changes with it.</p>
<p>ReactiveCocoa’s UI Binding is also an important concept playing a key role in implementing the MVVM design. This is because it is possible to separate the data processing code from the UI processing code by binding the properties of the ViewModel with the UI components in the View.</p>
<h3 id="heading-reactive-chain-reaction">Reactive Chain Reaction</h3>
<p>Now go back to the example code and see how the Property and UI Binding are being used. Let’s start with the process of activating the [Request verification code] Button when a phone number is entered. The Button’s BindingTarget subscribes to the input value change Signal generated by the continuousTextValues ​​of the TextField described above.</p>
<pre><code>requestVerifyNumberButton.reactive.isEnabled &amp;lt;~     phoneNumberTextField.reactive.continuousTextValues    .map { !($<span class="hljs-number">0</span>?.isEmpty ?? <span class="hljs-literal">true</span>) }
</code></pre><p>The isEnabled BindingTarget of requestVerifyNumberButton was bound to the input value change Signal of phoneNumberTextField and the &lt;~ operator was used in the process.</p>
<p>The isEnabled property of the Button is a Bool type property. The input value of TextField is a string type, so the value can not be directly assigned.</p>
<p>Therefore, when the string value is passed, it is changed to a Bool type through Signal’s map method. It is clear that <strong>stream data,</strong> which is a key advantage of Reactive Programming<strong>, is easy to process and can be expressed in a short and concise manner.</strong></p>
<p>Let’s take a look at the state change of Button, TextField, and Label depending on the value of verifyStep which occupies the greater part of the example.</p>
<pre><code><span class="hljs-keyword">var</span> verifyStep = MutableProperty&lt;PhoneNumberVerifyStep&gt;(...)
</code></pre><p>First, verifyStep is declared as a MutableProperty. verifyStep can now serve as a data stream, and UI Components can subscribe to a value change Signal from it. The value property returns the primitive value of verifyStep.</p>
<p>The following is UI Component Bindings to the Signal of verifyStep. Similarly, the &lt;~ operator connects the BindingTarget that changes the isHidden and text properties of the UI Components with the Signal from verifyStep. That is, if the value of verifyStep is changed, the UI attributes such as isHidden and text are changed accordingly.</p>
<pre><code>verifyNumberTextField.reactive.isHidden &lt;~ verifyStep    .map { $<span class="hljs-number">0</span> == .succeed }
</code></pre><pre><code>verifyButton.reactive.isHidden &lt;~ verifyStep.map { $<span class="hljs-number">0</span> == .succeed }
</code></pre><pre><code>statusLabel.reactive.isHidden &lt;~ verifyStep.map { !$<span class="hljs-number">0.</span>isVerifiedStep }
</code></pre><pre><code>statusLabel.reactive.text &lt;~ verifyStep.signal    .filter { $<span class="hljs-number">0.</span>isVerifiedStep }.map { $<span class="hljs-number">0</span> == .succeed ? ... }
</code></pre><p>Use the <strong>map</strong> method to bind the Enum type value called PhoneNumberVerifyStep to the Bool type property. Use the <strong>filter</strong> method to ensure that the text in the statusLabel changes only when verifyStep is .succeed or .failed.</p>
<p>Up to this point, the chain reaction between data and UI has been improved in a reactive way during the implementation of Phone Number Authentication. No more didSet observers are needed. <strong>Complex UI change methods have also disappeared.</strong></p>
<p>The Reactive approach allows us to define how a single UI component will change in the future with a concise representation. It also improves the readability of the code. Also, there are fewer things to change when adding or removing UI components.</p>
<p>Finally, let’s look at how to handle the UI Control Event through ReactiveCocoa.</p>
<h3 id="heading-handling-ui-control-events-with-reactivecocoa">Handling UI Control Events with ReactiveCocoa</h3>
<p>ReactiveCocoa also provides a way to handle UI control events as streams. Like the continuousTextValues ​​of the TextField we saw earlier, ReactiveCocoa has added a property that returns a Signal instance for the control event of the UI component. The Signal for the UI Event can be bound to the BindingTarget, or it can have an observer directly.</p>
<pre><code>verifyButton.reactive.controlEvents(.touchUpInside).observeValues {     self.api.getUsersVerify(...)        .on(value: { _ <span class="hljs-keyword">in</span>            self.verifyStep.value = .succeed        })        .on(failed: { error <span class="hljs-keyword">in</span>            self.verifyStep.value = .failed        })}
</code></pre><p>In the example, we added the Observer directly to the UI Event Signal. The controlEvents method returned a Signal for the touchUpInside event, and the observer handler was added via the observeValues ​​method.</p>
<p>The simple process of changing the Label’s text when the Button is touched is possible by binding through the &lt;~ operator.</p>
<pre><code>label.reactive.text &lt;~ button.reactive.controlEvents(.touchUpInside)    .map { _ <span class="hljs-keyword">in</span> <span class="hljs-string">"hello"</span> }
</code></pre><p>Let’s recap the process so far. If a signal occurs while subscribing to a stream of the UI Event, it calls the Remote API. Change the value of MutableProperty according to the value passed to the response handler of the asynchronous call. At the same time, a value change signal is generated from the stream of MutableProperty, and the UI that is bound to the change signal is changed.</p>
<p>Now we’ve changed the Phone Number Authentication example to conform to the definition of Reactive Programming. Most of the processing is done with stream subscription and UI binding.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>We have changed the traditional Phone Number Authentication to use Reactive programming. It’s not a new concept — Swift and Cocoa already provide many tools for asynchronous processing, UI event handling, and observer pattern implementation. However, using the Reactive way is more elegant and concise than the classic way. Also, there is an advantage that it can be used to design program structure like MVVM.</p>
<p>Everything in the programming world is related to <strong>how well we understand the code.</strong> It is important that it is easy it is to maintain. In this respect, adopting the reactive approach is a very smart decision. It is true that it is rather difficult to use for the first time. However, I am convinced that if you get used to it, you can code much more succinctly than before, and easily implement UI and user logic.</p>
<p>Let’s look again at the advantages of Reactive programming:</p>
<ul>
<li>The code that responds to changes in specific data or UI components is simplified.</li>
<li>Because you do not have to create a huge method of focused code that changes the UI, it becomes easier to deal with new states or add or remove UI components.</li>
<li>Functional coding allows you to write code that can focus on situations and roles.</li>
<li>With Observing and Binding, you can separate ViewController into ViewModel and View, which is a key factor in applying MVVM design.</li>
</ul>
<p>I hope that many developers will be able to code more happily through Reactive Programming. Thank you for reading this story.</p>
<p>I am writing about developing iOS applications using Swift. I would also appreciate your interest in the following articles.</p>
<p><a target="_blank" href="https://medium.com/@JinwooChoi/promise-syntax-with-reactiveswift-ae9b397a1bef"><strong>Promise Syntax with ReactiveSwift</strong></a><br><a target="_blank" href="https://medium.com/@JinwooChoi/promise-syntax-with-reactiveswift-ae9b397a1bef">_Use ReactiveSwift to write code similar to Promise in JavaScript._medium.com</a><a target="_blank" href="https://medium.com/@JinwooChoi/using-enums-in-swift-7d9cd7729758"><strong>Using Enums in Swift</strong></a><br><a target="_blank" href="https://medium.com/@JinwooChoi/using-enums-in-swift-7d9cd7729758">_How to handle the constants, raw values, and expressions of an Enum type through Swift._medium.com</a><a target="_blank" href="https://medium.com/@JinwooChoi/passing-parameters-to-restful-api-with-swift-codable-d78eb78f7b1"><strong>Passing parameters to Restful API with Swift Codable</strong></a><br><a target="_blank" href="https://medium.com/@JinwooChoi/passing-parameters-to-restful-api-with-swift-codable-d78eb78f7b1">_How not only the data received from the Restful API, but also the data to be transmitted, can be handled easily through…_medium.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A quick introduction to Functional Reactive Programming (FRP) ]]>
                </title>
                <description>
                    <![CDATA[ By Navdeep Singh FRP represents an intersection of two programming paradigms. But, before we dig deeper into the concepts, we need to know a bit more about some basic terms. FRP: reacting to events Imperative programming Traditionally, we write code... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/functional-reactive-programming-frp-imperative-vs-declarative-vs-reactive-style-84878272c77f/</link>
                <guid isPermaLink="false">66c34b14a7aea9fc97bdfb25</guid>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 11 Mar 2018 11:26:26 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*2K8v7kw0Nz1ncohxmil5KA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Navdeep Singh</p>
<p>FRP represents an intersection of two programming paradigms. But, before we dig deeper into the concepts, we need to know a bit more about some basic terms.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/zmvecVovUlqx5GTj1gMqLVhLKHEiES7Fy42x" alt="Image" width="800" height="341" loading="lazy">
<em>FRP: reacting to events</em></p>
<h3 id="heading-imperative-programming">Imperative programming</h3>
<p>Traditionally, we write code that describes how it should solve a problem. Each line of code is sequentially executed to produce a desired outcome, which is known as imperative programming. The imperative paradigm forces programmers to write “how” a program will solve a certain task. Note that in the previous statement, the keyword is “how.”</p>
<p>Here’s an example:</p>
<pre><code><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]<span class="hljs-keyword">var</span> numbersLessThanFive = [Int]()<span class="hljs-keyword">for</span> index <span class="hljs-keyword">in</span> <span class="hljs-number">0.</span>.&lt;numbers.count     {    <span class="hljs-keyword">if</span> numbers[index] &lt; <span class="hljs-number">5</span>         {        numbersLessThanFive.append(numbers[index])        }    }
</code></pre><p>As you can see, we sequentially execute a series of instructions to produce a desired output.</p>
<h3 id="heading-functional-programming">Functional programming</h3>
<p>Functional programming is a programming paradigm where you model everything as a result of a function that avoids changing state and mutating data. We will discuss concepts such as state and data mutability and their importance in subsequent sections, but for reference:</p>
<ul>
<li>consider <strong>state</strong> as one of the different permutations and combinations that your program can have at any given time during its execution</li>
<li><strong>data mutability</strong> is the concept where a given dataset might change over a given course of time during program execution.</li>
</ul>
<p>The same example that was given using imperative programming can be used in the following way using the functional approach:</p>
<pre><code><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]<span class="hljs-keyword">let</span> numbersLessThanFive = numbers.filter { $<span class="hljs-number">0</span> &lt; <span class="hljs-number">5</span> }
</code></pre><p>We feed the filter function with a closure containing a certain criterion. That criterion is then applied to each element in the numbers array, and the resulting array contains elements that satisfy our criteria.</p>
<p><strong>Notice the declaration of the two arrays in both the examples.</strong></p>
<p>In the first example, the <code>numbersLessThanFive</code> array was declared as a <code>var</code>, whereas in the second example, the same array was declared as a <code>let</code>.</p>
<p>Does it ring some bells?</p>
<p>Which approach is better, which array is safer to work with?</p>
<p>What if more than one thread is trying to work with the same array and its elements?</p>
<p>Isn’t a constant array more reliable?</p>
<h3 id="heading-reactive-programming">Reactive programming</h3>
<p>Reactive programming is the practice of programming with asynchronous data streams or event streams. An <strong>event stream</strong> can be anything like keyboard inputs, button taps, gestures, GPS location updates, accelerometer, and iBeacon. You can listen to a stream and react to it accordingly.</p>
<p>You might have heard about reactive programming, but it might have sounded too intimidating, scary, or cryptic to even try out. You might have seen something like this:</p>
<pre><code><span class="hljs-keyword">var</span> twoDimensionalArray = [ [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>], [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>] ]<span class="hljs-keyword">let</span> flatArray = twoDimensionalArray.flatMap { array <span class="hljs-keyword">in</span>    <span class="hljs-keyword">return</span> array.map { integer <span class="hljs-keyword">in</span>        <span class="hljs-keyword">return</span> integer * <span class="hljs-number">2</span>    }}print(flatArray)Output : [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>, <span class="hljs-number">12</span>]
</code></pre><p>At first glance, the preceding code might feel a bit obscure, and this might be the reason you turned your back on this style of programming. Reactive programming, as we mentioned earlier, is programming with event streams.</p>
<p>However, the bigger question still remains unanswered. <strong>What is functional reactive programming (FRP)?</strong></p>
<p>FRP is the <strong>combination</strong> of functional and reactive paradigms. In other words, it is reacting to data streams using the functional paradigm. FRP is not a utility or a library — it changes the way you architect your applications and the way you think about your applications.</p>
<p>In the next blog I will talk about basic building blocks of reactive programming — till then stay tuned and enjoy reading:)</p>
<p>To have a solid grasp over reactive concepts and write iOS applications in RxSwift you can read my book: <a target="_blank" href="https://www.amazon.com/Reactive-Programming-Swift-easy-maintain-ebook/dp/B078MHNSL1/ref=asap_bc?ie=UTF8">Reactive programming in Swift 4</a>.</p>
<p>More of my projects and downloadable code are in <a target="_blank" href="https://github.com/NavdeepSinghh">my public github repos</a></p>
<p>You can read more about the topic <a target="_blank" href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">here</a></p>
<p>Thanks for reading, please share it if you found it useful :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Reactive programming and Observable sequences with RxJS in Node.js ]]>
                </title>
                <description>
                    <![CDATA[ By Enrico Piccinin Dealing with asynchronous non-blocking processing has always been the norm in the JavaScript world, and now is becoming very popular in many other contexts. The benefits are clear: an efficient use of resources. But the benefits co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rxjs-and-node-8f4e0acebc7c/</link>
                <guid isPermaLink="false">66d4608ec7632f8bfbf1e47b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RxJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 23 Dec 2017 11:16:07 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*gpmVC7PYhD3ZYHBYltyeXw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Enrico Piccinin</p>
<p>Dealing with asynchronous non-blocking processing has always been the norm in the JavaScript world, and now is becoming very popular in many other contexts. The benefits are clear: an efficient use of resources. But the benefits come at a cost: a non-trivial increase in complexity.</p>
<p>Over time, vendors and the open source community have tried to find ways to reduce such complexity without compromising the benefits.</p>
<p>Asynchronous processing started with ‘callbacks’, then came Promise and Future, async and await. Recently another kid has come to town — <a target="_blank" href="http://reactivex.io/">ReactiveX</a> with its various language implementations — bringing the developers a new powerful tool, the Observable.</p>
<p>In this article, we want to show how Observables implemented by <a target="_blank" href="http://reactivex.io/rxjs/">RxJs</a> (the JavaScript embodiment of ReactiveX) can simplify code to be executed with Node.js, the popular server-side JavaScript non-blocking environment.</p>
<h3 id="heading-a-simple-use-case-read-transform-write-and-log">A simple use case — Read, Transform, Write, and Log</h3>
<p>To make our reasoning concrete, let’s start from a simple use case. Let’s assume we need to read the files contained in <code>**Source Dir**</code>, transform their content and write the new transformed files in a <code>**Target Dir**</code><em>,</em> while keeping a log of the files we have created.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/t6BDM5ShfozMhO6juTt2pT5hoxj6C-XnQe8G" alt="Image" width="800" height="361" loading="lazy">
<em>Read — Transform — Write — Log</em></p>
<h3 id="heading-synchronous-implementation">Synchronous implementation</h3>
<p>The synchronous implementation of this use case is pretty straightforward. In a sort of pseudo code representation, we could think of something like:</p>
<pre><code>read the names <span class="hljs-keyword">of</span> the files <span class="hljs-keyword">of</span> Source Dir
   <span class="hljs-keyword">for</span> each file name
      read the file
      transform the content
      write the <span class="hljs-keyword">new</span> file <span class="hljs-keyword">in</span> Target Dir
      log the name <span class="hljs-keyword">of</span> the <span class="hljs-keyword">new</span> file
   end <span class="hljs-keyword">for</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am done'</span>)
</code></pre><p>There is nothing special to comment here. We can just say that we are sure of the sequence of execution of each line and that we are sure that things will happen as described by the following flow of events. Each circle corresponds to the completion of an I/O operation.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VkuJvfZCN7Ps5vLDx4OvCxcU1pfo3MsHYkGc" alt="Image" width="800" height="86" loading="lazy">
<em>The sequence of events in a synchronous world</em></p>
<h3 id="heading-what-happens-in-an-asynchronous-non-blocking-environment-like-nodejs">What happens in an asynchronous non-blocking environment like Node.js</h3>
<p>Node.js is an asynchronous non-blocking execution environment for JavaScript. Non-blocking means that Node.js does not wait for I/O or Network operations to complete before moving to the execution of the next line of code.</p>
<h4 id="heading-processing-one-file"><strong>Processing one file</strong></h4>
<p>Reading and writing files are I/O operations where Node.js shows its non-blocking nature. If a Node.js program asks for a file to read, it has to provide a function to be executed when the file content is available (the so called <strong>callback</strong>) and then immediately move on to the next operation to execute.</p>
<p>Let’s consider the case of just <strong>one file</strong>. Reading, transforming, writing <strong>one</strong> file and updating the log in Node.js looks something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>; <span class="hljs-comment">// Node module to access file system</span>
<span class="hljs-keyword">const</span> fileName = <span class="hljs-string">'one-file.txt'</span>;
fs.readFile(fileName, callback(err, data) =&gt; {
   <span class="hljs-keyword">const</span> newContent = transform(data);
   <span class="hljs-keyword">const</span> newFileName = newFileName(fileName); <span class="hljs-comment">// calculate new name</span>
   fs.writeFile(newFileName, newContent, <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
      <span class="hljs-keyword">if</span>(err) {<span class="hljs-comment">// handle error};</span>
      fs.appendFile(<span class="hljs-string">'log.txt'</span>, newFileName  + <span class="hljs-string">' written'</span>, err = {
         <span class="hljs-keyword">if</span> (err) {<span class="hljs-comment">// handle error}</span>
      });
   });
})
</code></pre>
<p>The syntax may look a bit convoluted with 2 levels of indentation, but if we think of what happens in terms of events we can still precisely foresee the sequence:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CZESn-CUe78yiDYRe0a79MZH81ZZuAu7mBrJ" alt="Image" width="800" height="87" loading="lazy">
<em>Sequence of events in Node while transforming 1 file</em></p>
<h4 id="heading-the-paradise-of-promise"><strong>The paradise of Promise</strong></h4>
<p>This is the use case where JavaScript Promise shines. Using Promise we can make the code look again sequential, without interfering with the asynchronous nature of Node.js.</p>
<p>Assuming we can access functions that perform read and write operations on file and return a Promise, then our code would look like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fileName = <span class="hljs-string">'my-file.txt'</span>;
readFilePromise(fileName)
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
   <span class="hljs-keyword">const</span> newContent = transform(data);
   <span class="hljs-keyword">const</span> newFileName = newFileName(fileName); <span class="hljs-comment">// build the new name</span>
   <span class="hljs-keyword">return</span> writeFilePromise(newFileName, newContent)
})
.then(<span class="hljs-function"><span class="hljs-params">newFileName</span> =&gt;</span> appendFile(<span class="hljs-string">'log.txt'</span>, newFileName))
.then(<span class="hljs-function"><span class="hljs-params">newFileName</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(newFileName + <span class="hljs-string">' written'</span>))
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-comment">// handle error)</span>
</code></pre>
<p>There are several ways to transform Node.js functions in <code>Promise</code> based functions. This is one example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readFilePromise</span>(<span class="hljs-params">fileName: string</span>): <span class="hljs-title">Promise</span>&lt;<span class="hljs-title">Buffer</span>&gt;</span>{
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
      fs.readFile(fileName, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data: Buffer</span>) </span>{
         <span class="hljs-keyword">if</span>(err !== <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> reject(err);
         resolve(data);
      });
   });
}
</code></pre>
<h4 id="heading-processing-many-files"><strong>Processing many files</strong></h4>
<p>If we return to the original use case, where we have to transform all the files contained in a Directory, the complexity increases and Promises start showing some limits.</p>
<p>Let’s look at the events the Node.js implementation needs to manage:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PRMavRZ7dF0oaWIHXqkCq6-e0Xfm0HR5m1-u" alt="Image" width="800" height="253" loading="lazy">
<em>Sequence of events when transforming many files in parallel</em></p>
<p>Each circle represents the completion of one I/O operation, either read or write. Every line represents the processing of one specific file, or a chain of Promises.</p>
<p>Given the non-blocking nature of Node.js, there is no certainty on the sequence in time of such events. It is possible that we will finish writing <code>**File2**</code> before we finish reading <code>**File3**</code>.</p>
<p>The parallel processing of each file makes the use of Promises more complex (at the end of this article, a Promise based implementation is provided). This is the scenario where ReactiveX — RxJs in particular — and Observable shine and allow you to build elegant solutions.</p>
<h3 id="heading-what-are-observables-and-what-can-you-do-with-them">What are Observables and what can you do with them?</h3>
<p>There are many places where formal definitions of Observables are detailed, starting from the official site of <a target="_blank" href="http://reactivex.io/intro.html">ReactiveX</a>.</p>
<p>Here I just want to remind you of a couple of properties that have always gotten my attention:</p>
<ul>
<li>Observable models a <strong>stream of events</strong></li>
<li>Observable is the <strong>“push”</strong> brother of Iterable, which is “pull”</li>
</ul>
<p>As the “push” brother of Iterable, Observable offers developers many of the cool features provided by Iterables such as:</p>
<ul>
<li>Transform “streams of events” or Observables, via operators such as <code>map</code>, <code>filter</code>and <code>skip</code></li>
<li>Apply functional programming style</li>
</ul>
<p>One additional very important thing that Observable offers is subscription. Via subscription, the code can apply “side effects” to events and perform specific actions when specific events happen, such as when errors occur or the stream of events completes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZXgqj1SdhavRZdcReV9aBvtTnLZ3r8jODhNz" alt="Image" width="800" height="389" loading="lazy">
<em>The subscribe interface of Observable</em></p>
<p>As you can see, the Observable interface gives developers the possibility to provide three different functions which define what to do respectively when: an event is emitted with its data, an error occurs, or the stream of events completes.</p>
<p>I guess all of the above may sound very theoretical to those who have not yet played with Observable, but hopefully the next part of the discussion, which is focused on our use case, will make these concepts more concrete.</p>
<h3 id="heading-implementation-of-the-read-transform-write-and-log-use-case-via-observable">Implementation of the Read, Transform, Write, and Log use case via Observable</h3>
<p>Our use case starts with reading the list of files contained in <code>**Source Dir**</code>. So, let’s start from there.</p>
<h4 id="heading-read-all-the-file-names-contained-in-a-directory"><strong>Read all the file names contained in a Directory</strong></h4>
<p>Let’s assume we have access to a function which receives as input the name of a directory and returns an Observable which emits the list of file names of the directory once the directory tree structure has been read.</p>
<pre><code>readDirObservable(dirName: string) : Observable&lt;<span class="hljs-built_in">Array</span>&lt;string&gt;&gt;
</code></pre><p>We can subscribe to this Observable and when all file names have been read, start doing something with them:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BeSolRYnvm1Cj0rhkQtZXbtqkopSZ-yCELo8" alt="Image" width="800" height="192" loading="lazy">
<em>Subscription to an Observable which emits when the directory has been read</em></p>
<h4 id="heading-read-a-list-of-files"><strong>Read a list of files</strong></h4>
<p>Let’s assume now that we can access a function which receives as input a list of file names and emits each time a file has been read (it emits the content of the file <code>Buffer</code>, and its name <code>string</code>).</p>
<pre><code>readFilesObservable(fileList: <span class="hljs-built_in">Array</span>&lt;string&gt;) 
   : Observable&lt;{<span class="hljs-attr">content</span>: Buffer, <span class="hljs-attr">fileName</span>: string}&gt;
</code></pre><p>We can subscribe to such <code>Observable</code> and start doing something with the content of the files.</p>
<h4 id="heading-combining-observables-switchmap-operator">Combining Observables — <em>switchMap</em> operator</h4>
<p>We have now two Observables, one that emits a list of file names when the directory has been read and one that emits every time a file is read.</p>
<p>We need to combine them to implement the first step of our use case, which is: when <code>readDirObservable</code> emits, we need to <strong>switch</strong> to <code>readFilesObservable</code> .</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iWmO0g9KdUw64scmcB5OGgbsOJarDfwyIGZg" alt="Image" width="800" height="165" loading="lazy">
<em>switchMap operator</em></p>
<p>The trick here is performed by the <code>switchMap</code> operator. The code looks like:</p>
<pre><code>readDirObservable(dirName)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data.fileName + ‘ read’), <span class="hljs-comment">// do stuff with the data received</span>
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files read’)
)
</code></pre><p>We must mention that the <code>switchMap</code> operator is more powerful than this. Its full power though can not be appreciated in this simple use case, and its full description is outside the scope of this post. If you are interested, this is an <a target="_blank" href="https://blog.angular-university.io/rxjs-switchmap-operator/">excellent article</a> that describes in detail <code>switchMap</code>.</p>
<h4 id="heading-observable-generating-a-stream-of-observables"><strong>Observable generating a stream of Observables</strong></h4>
<p>We have now a stream of events representing the completion of a <code>read</code> operation. After the <code>read</code> we need to do a transformation of the content that, for sake of simplicity, we assume to be synchronous, and then we need to save the transformed content in a new file.</p>
<p>But writing a new file is again an I/O operation, or a non-blocking operation. So every ‘file-read-completion’ event starts a new path of elaboration that receives as input the content and the name of the source file, and emits when the new file is written in the <code>Target Dir</code> (the event emitted carries the name of the file written).</p>
<p>Again, we assume that we’re able to access a function that emits as soon as the write operation is completed, and the data emitted is the name of the file written.</p>
<pre><code>writeFileObservable(fileName: string, <span class="hljs-attr">content</span>: Buffer) :            Observable&lt;string&gt;
</code></pre><p>In this case, we have different “write-file” Observables, returned by the <code>writeFileObservable</code> function, which emits independently. It would be nice to <strong>merge</strong> them into a new Observable which emits any time each of these “write-file” Observables emit.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/uNh9nBU32X6SbsDi-SAmYy90FhR4we4XLcXv" alt="Image" width="800" height="374" loading="lazy">
<em>A stream of Observables we would like to merge</em></p>
<p>With ReactiveX (or RxJs in JavaScript) we can reach this result using the <code>mergeMap</code> operator (also known as a <strong>flatMap</strong>). This is what the code looks like:</p>
<pre><code>readDirObservable(dir)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> transform(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> writeFileObservable(data.fileName, data.content))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data.fileName + ‘ written’),
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files written’)
)
</code></pre><p>The <code>mergeMap</code> operator has created a new Observable, the <code>writeFileObservable</code> as illustrated in the following diagram:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/reYH02KG9yTsgGuI7cTiPFMCTURzBsFRC07D" alt="Image" width="800" height="260" loading="lazy">
<em>Observable returned by mergeMap operator</em></p>
<h4 id="heading-so-what">So what?</h4>
<p>Applying the same approach, if we just imagine that we have a new function of <code>writeLogObservable</code>, that writes a line on the log as soon as the file is written and emits the file name as soon as the log is updated, the final code for our use case would look like:</p>
<pre><code>readDirObservable(dir)
.switchMap(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> readFilesObservable(fileList))
.map(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> transform(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> writeFileObservable(data.fileName, data.content))
.mergeMap(<span class="hljs-function"><span class="hljs-params">fileName</span> =&gt;</span> writeLogObservable(fileName))
.subscribe(
      <span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(fileName + ‘ logged’),
      <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error },</span>
      <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘All files have been transformed’)
)
</code></pre><p>We do not have indentations introduced by the callbacks.</p>
<p>Time flows along the vertical axis only, so we can read the code line by line and reason about what is happening line after line.</p>
<p>We have adopted a functional style.</p>
<p>In other words, we have seen the benefits of Observable in action.</p>
<h3 id="heading-create-observable-from-functions-with-callbacks">Create Observable from functions with callbacks</h3>
<p>I hope you now think that this looks pretty cool. But even in this case you may have one question. All the functions that make this code cool just do not exist. There is no <code>readFilesObservable</code> or <code>writeFileObservable</code> in standard Node.js libraries. How can we create them?</p>
<h4 id="heading-bindcallback-and-bindnodecallback"><strong>bindCallback and bindNodeCallback</strong></h4>
<p>A couple of functions provided by Observable, namely <code>bindCallback</code>(and <code>bindNodeCallback</code>) come to our rescue.</p>
<p>The core idea behind them is to provide a mechanism to transform a function <code>f</code> which accepts a callback <code>cB(cBInput)</code> as input parameter into a function which returns an Observable <code>obsBound</code> which emits <code>cBInput</code>. In other words, it transforms the <strong>invocation</strong> of the <code>cB</code> in the <strong>emission</strong> of <code>cBInput</code>.</p>
<p>The subscriber of <code>obsBound</code> can define the function which will process <code>cBInput</code> (which plays the same role as <code>cB(cBInput)</code>). The convention applied is that the callback function <code>cB(cBInput)</code> must be the last argument of<code>f</code>.</p>
<p>It is probably easier to understand the mechanism looking at the following diagram:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SfAvPHIPSPJmnk3VLeW6ioBOCITEpiebo-Bf" alt="Image" width="800" height="378" loading="lazy">
<em>From a function to an Observable</em></p>
<p>The starting point, the function <strong>f(x, cb)</strong> is the same in the two cases. The result (what is printed on the console) is the same in the two cases.</p>
<p>What is different is how the result is obtained. In the first case the result is determined by the callback function passed as input. In the second case it is determined by the function defined by the subscriber.</p>
<p>Another way of considering how <code>bindCallback</code> works is to look at the transformation it performs, as illustrated in the diagram below.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/MJ-tn3TsJhIDDEPt6ymYxBxgMJ1GYyqNQfHA" alt="Image" width="800" height="134" loading="lazy">
<em>Transformation performed by bindCallback</em></p>
<p>The first argument of <code>f</code> becomes the value passed to the new function <code>fBound</code>. The arguments used as parameters of the callback <code>cb</code> become the values emitted by the new Observable returned by <code>fBound</code>.</p>
<p><code>bindNodeCallback</code> is a variation of <code>bindCallback</code> based on the convention that the callback function has an <strong>error</strong> parameter as the first parameter, along with the Node.js convention <code>fs.readFile(err, cb)</code>.</p>
<h4 id="heading-create-observables-from-non-callback-functions"><strong>Create Observables from non-callback functions</strong></h4>
<p><code>bindNodeCallback</code> has been designed to work with functions which expect a callback as the last argument of their input, but we can make it work also with other functions.</p>
<p>Let’s consider the standard Node.js function <code>readLine</code>. This is a function used to read files line by line. The following example shows as it works:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/41zopDeXW8stNTeBo2BmXMswEucES7U4WASG" alt="Image" width="800" height="166" loading="lazy">
<em>readLine function</em></p>
<p>Each line read is pushed into the <code>lines</code> array. When the file is completely read, the function <code>processLinesCb</code> is called.</p>
<p>Imagine now that we define a new function,<code>_readLines</code>, which wraps the logic defined above as shown by the following snippet:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/2SxYnanPtydSbSaJmkEGmxsWSHU7QIAToPpu" alt="Image" width="800" height="138" loading="lazy">
<em>readLine function wrapped by a callback function</em></p>
<p>Once all lines are read, they are processed by the function <code>processLinesCb</code>, which is the last input parameter of <code>_readLines</code>. <code>_readLines</code> is therefore a function that can be treated by <code>bindCallback</code>. Through this trick we can transform the Node.js function <code>fs.readLine</code> into an Observable using the usual <code>bindCallback</code> function as follows:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FMEHXXKXwbucYZ4s1sVj9OkuavNPUMw972va" alt="Image" width="800" height="69" loading="lazy">
<em>readLine as Observable</em></p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Asynchronous non-blocking processing is complex by nature. Our minds are used to think sequentially — this is true at least for those of us who started coding few years ago. We often find it challenging to reason about what is really happening in these environments. The callback-hell is just around the corner.</p>
<p>Promises and Futures have simplified some of the most frequent cases such as ‘one time’ asynchronous events, the ‘request now — respond later’ scenario typical of HTTP requests.</p>
<p>If we move from ‘one time’ events to ‘event streams’ Promises start showing some limitations. In such cases we may find ReactiveX and Observables a very powerful tool.</p>
<h4 id="heading-as-promised-the-promise-based-implementation-of-our-use-case"><strong>As promised: the Promise-based implementation of our use case</strong></h4>
<p>This is an implementation of the same use case based on Promises:</p>
<pre><code><span class="hljs-keyword">const</span> promises = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">Promise</span>&gt;();
readDirPromise(dir)
.then(<span class="hljs-function"><span class="hljs-params">fileList</span> =&gt;</span> {
   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> file <span class="hljs-keyword">of</span> fileList) {promises.push(
         readFilePromise(file)
         .then(<span class="hljs-function"><span class="hljs-params">file_content</span> =&gt;</span> transform(file_content))
         .then(<span class="hljs-function"><span class="hljs-params">file</span> =&gt;</span> writeLogPromise(file))
      );
   }
   <span class="hljs-keyword">return</span> promises;
}
.then(<span class="hljs-function"><span class="hljs-params">promises</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.all(promises))
.then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(‘I am done’))
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-comment">// manage error })</span>
</code></pre> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Rx — If the Operators could speak! ]]>
                </title>
                <description>
                    <![CDATA[ By Ahmed Rizwan If the operators could talk, how exactly would they tell us what they do? In order to take full advantage of Rx, you need a clear understanding of what Rx Operators are and what they do. This is what the Operators would be telling the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rx-if-the-operators-could-speak-58567c4618f1/</link>
                <guid isPermaLink="false">66c35e2f258ebfc3dc8f1f7c</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mobile ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ rx ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 13 Sep 2016 20:51:00 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*U9DEpj0xpch6t3VdCxAZVA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ahmed Rizwan</p>
<p>If the operators could talk, how exactly would they tell us what they do?</p>
<p>In order to take full advantage of Rx, you need a clear understanding of what Rx Operators are and what they do.</p>
<p>This is what the Operators would be telling the observables if they could talk when we use them.</p>
<p>For this article, I’ll assume that you already know what Rx is. If not, go <a target="_blank" href="https://medium.com/@ahmedrizwan/rxandroid-and-kotlin-part-1-f0382dc26ed8#.vundiz1fq">read this</a>. Or just simply google Rx and you’ll find a ton of helpful articles, tutorials, and videos.</p>
<h3 id="heading-creational-operators"><strong>Creational Operators</strong></h3>
<h4 id="heading-createhttpreactivexiodocumentationoperatorscreatehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/create.html">Create</a></h4>
<blockquote>
<p>I tell you what to emit, when to terminate, and what error to throw. ‘Cause I’m the boss.</p>
</blockquote>
<h4 id="heading-deferhttpreactivexiodocumentationoperatorsdeferhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/defer.html">Defer</a></h4>
<blockquote>
<p>You only get to “create” yourself once someone subscribes to you. And it’ll be a brand new version of yourself every single time.</p>
</blockquote>
<h4 id="heading-emptyhttpreactivexiodocumentationoperatorsempty-never-throwhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/empty-never-throw.html">Empty</a></h4>
<blockquote>
<p>Hm. Emit nothing. And then die, please.</p>
</blockquote>
<h4 id="heading-neverhttpreactivexiodocumentationoperatorsempty-never-throwhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/empty-never-throw.html">Never</a></h4>
<blockquote>
<p>Emit nothing. And don’t… ever… terminate.</p>
</blockquote>
<h4 id="heading-throwhttpreactivexiodocumentationoperatorsempty-never-throwhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/empty-never-throw.html">Throw</a></h4>
<blockquote>
<p>Emit nothing, and then throw an error, OK?</p>
</blockquote>
<h4 id="heading-fromhttpreactivexiodocumentationoperatorsfromhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/from.html">From</a></h4>
<blockquote>
<p>I’ll give you some objects, then you emit them right back at me.</p>
</blockquote>
<h4 id="heading-intervalhttpreactivexiodocumentationoperatorsintervalhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/interval.html">Interval</a></h4>
<blockquote>
<p>How about this: you emit items. But not immediately. Send them back, one by one, after certain “intervals.”</p>
</blockquote>
<h4 id="heading-justhttpreactivexiodocumentationoperatorsjusthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/just.html">Just</a></h4>
<blockquote>
<p>I need just one thing back from you. Just one.</p>
</blockquote>
<h4 id="heading-rangehttpreactivexiodocumentationoperatorsrangehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/range.html">Range</a></h4>
<blockquote>
<p>I give you a range of integers, then you emit back all the values in that range.</p>
</blockquote>
<h4 id="heading-repeathttpreactivexiodocumentationoperatorsrepeathtml"><a target="_blank" href="http://reactivex.io/documentation/operators/repeat.html">Repeat</a></h4>
<blockquote>
<p>How about you emit that same object repeatedly.</p>
</blockquote>
<h4 id="heading-starthttpreactivexiodocumentationoperatorsstarthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/start.html">Start</a></h4>
<blockquote>
<p>Ok. I have a function. When it returns, you start emitting. But only when it returns. Got it?</p>
</blockquote>
<h4 id="heading-timerhttpreactivexiodocumentationoperatorstimerhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/timer.html">Timer</a></h4>
<blockquote>
<p>So you got an item. Don’t emit it just yet. I’ll tell you the exact time when you should emit it. Don’t jump the gun.</p>
</blockquote>
<h3 id="heading-transformational-operators">Transformational Operators</h3>
<h4 id="heading-bufferhttpreactivexiodocumentationoperatorsbufferhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/buffer.html">Buffer</a></h4>
<blockquote>
<p>Ok, so here’s the deal. Whatever it is you normally emit, well don’t emit that. Instead ,collect the items into bundles over time. And send bundles instead. ‘Cause I want bundles!</p>
</blockquote>
<h4 id="heading-flatmaphttpreactivexiodocumentationoperatorsflatmaphtml"><a target="_blank" href="http://reactivex.io/documentation/operators/flatmap.html">FlatMap</a></h4>
<blockquote>
<p>So, like, if you have lists of items and there’s another observable that’s full of items, can you please “flatten” yourself and that observable so you can just send items?</p>
</blockquote>
<h4 id="heading-maphttpreactivexiodocumentationoperatorsmaphtml"><a target="_blank" href="http://reactivex.io/documentation/operators/map.html">Map</a></h4>
<blockquote>
<p>Transform each item into another item.</p>
</blockquote>
<h4 id="heading-scanhttpreactivexiodocumentationoperatorsscanhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/scan.html">Scan</a></h4>
<blockquote>
<p>Transform each item into another item, like you did with map. But also include the “previous” item when you get around to doing a transform.</p>
</blockquote>
<h3 id="heading-filtering-operators">Filtering Operators</h3>
<h4 id="heading-debouncehttpreactivexiodocumentationoperatorsdebouncehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/debounce.html">Debounce</a></h4>
<blockquote>
<p>Only emit if a certain amount of time is passed.</p>
</blockquote>
<h4 id="heading-distincthttpreactivexiodocumentationoperatorsdistincthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/distinct.html">Distinct</a></h4>
<blockquote>
<p>Emit only distinct items. All right?</p>
</blockquote>
<h4 id="heading-elementathttpreactivexiodocumentationoperatorselementathtml"><a target="_blank" href="http://reactivex.io/documentation/operators/elementat.html">ElementAt</a></h4>
<blockquote>
<p>I tell you the index. You emit the item at that index.</p>
</blockquote>
<h4 id="heading-filterhttpreactivexiodocumentationoperatorsfilterhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/filter.html">Filter</a></h4>
<blockquote>
<p>I give you a criteria. You give me items that pass the criteria.</p>
</blockquote>
<h4 id="heading-firsthttpreactivexiodocumentationoperatorsfirsthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/first.html">First</a></h4>
<blockquote>
<p>Just give me back the first item.</p>
</blockquote>
<h4 id="heading-ignoreelementshttpreactivexiodocumentationoperatorsignoreelementshtml"><a target="_blank" href="http://reactivex.io/documentation/operators/ignoreelements.html">IgnoreElements</a></h4>
<blockquote>
<p>Do not, I repeat, do not emit a single item. And then die.</p>
</blockquote>
<h4 id="heading-lasthttpreactivexiodocumentationoperatorslasthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/last.html">Last</a></h4>
<blockquote>
<p>Just give me back the last item.</p>
</blockquote>
<h4 id="heading-samplehttpreactivexiodocumentationoperatorssamplehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/sample.html">Sample</a></h4>
<blockquote>
<p>I give you an interval. You give me only the most recent items from that that interval.</p>
</blockquote>
<h4 id="heading-skiphttpreactivexiodocumentationoperatorsskiphtml"><a target="_blank" href="http://reactivex.io/documentation/operators/skip.html">Skip</a></h4>
<blockquote>
<p>OK, skip the first n items, would you?</p>
</blockquote>
<h4 id="heading-skiplasthttpreactivexiodocumentationoperatorsskiplasthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/skiplast.html">SkipLast</a></h4>
<blockquote>
<p>Skip the last n item s. Yeah, those ones.</p>
</blockquote>
<h4 id="heading-takehttpreactivexiodocumentationoperatorstakehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/take.html">Take</a></h4>
<blockquote>
<p>Emit only the first n items.</p>
</blockquote>
<h4 id="heading-takelasthttpreactivexiodocumentationoperatorstakelasthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/takelast.html">TakeLast</a></h4>
<blockquote>
<p>Emit only the last n items.</p>
</blockquote>
<h3 id="heading-combining-operators">Combining Operators</h3>
<h4 id="heading-mergehttpreactivexiodocumentationoperatorsmergehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/merge.html">Merge</a></h4>
<blockquote>
<p>Here are two observables. Let’s pretend they’re only one observable.</p>
</blockquote>
<h4 id="heading-startwithhttpreactivexiodocumentationoperatorsstartwithhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/startwith.html">StartWith</a></h4>
<blockquote>
<p>Here are two observables. But I get to tell you which one to start with.</p>
</blockquote>
<h4 id="heading-combinelatesthttpreactivexiodocumentationoperatorscombinelatesthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/combinelatest.html">CombineLatest</a></h4>
<blockquote>
<p>Here are two observables. Between the two, make pairs of the latest items.</p>
</blockquote>
<h4 id="heading-ziphttpreactivexiodocumentationoperatorsziphtml"><a target="_blank" href="http://reactivex.io/documentation/operators/zip.html">Zip</a></h4>
<blockquote>
<p>Here are two observables. But I tell you how to combine their items (through a function, of course).</p>
</blockquote>
<h3 id="heading-handling-errors">Handling Errors</h3>
<h4 id="heading-catchhttpreactivexiodocumentationoperatorscatchhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/catch.html">Catch</a></h4>
<blockquote>
<p>After an error is thrown, continue on with the emits.</p>
</blockquote>
<h4 id="heading-retryhttpreactivexiodocumentationoperatorsretryhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/retry.html">Retry</a></h4>
<blockquote>
<p>After an error is thrown, restart from the very beginning.</p>
</blockquote>
<h3 id="heading-utility">Utility</h3>
<h4 id="heading-delayhttpreactivexiodocumentationoperatorsdelayhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/delay.html">Delay</a></h4>
<blockquote>
<p>Just add a delay before you start emitting, OK?</p>
</blockquote>
<h4 id="heading-observeonhttpreactivexiodocumentationoperatorsobserveonhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/observeon.html">ObserveOn</a></h4>
<blockquote>
<p>“Observational” code should run on this particular thread.</p>
</blockquote>
<h4 id="heading-subscribeonhttpreactivexiodocumentationoperatorssubscribeonhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/subscribeon.html">SubscribeOn</a></h4>
<blockquote>
<p>“Subscription” code should run on this particular thread.</p>
</blockquote>
<h4 id="heading-subscribehttpreactivexiodocumentationoperatorssubscribehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/subscribe.html">Subscribe</a></h4>
<blockquote>
<p>You can start emitting now. <em>music intensifies</em></p>
</blockquote>
<h4 id="heading-timeintervalhttpreactivexiodocumentationoperatorstimeintervalhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/timeinterval.html">TimeInterval</a></h4>
<blockquote>
<p>OK, so observables send back items, right? Instead, I want you to send the time intervals back. Like the time differences between each emission.</p>
</blockquote>
<h4 id="heading-timeouthttpreactivexiodocumentationoperatorstimeouthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/timeout.html">TimeOut</a></h4>
<blockquote>
<p>Set a TimeOut on each emission. And if an item doesn’t get emitted within that time, just throw an error <em>?</em></p>
</blockquote>
<h3 id="heading-conditional-and-boolean">Conditional and Boolean</h3>
<h4 id="heading-allhttpreactivexiodocumentationoperatorsallhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/all.html">All</a></h4>
<blockquote>
<p>If all items fulfill a certain criteria, return true.</p>
</blockquote>
<h4 id="heading-ambhttpreactivexiodocumentationoperatorsambhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/amb.html">Amb</a></h4>
<blockquote>
<p>Here are at least two observables. Give me the one that starts emitting first.</p>
</blockquote>
<h4 id="heading-containshttpreactivexiodocumentationoperatorscontainshtml"><a target="_blank" href="http://reactivex.io/documentation/operators/contains.html">Contains</a></h4>
<blockquote>
<p>If I ask for an item, can you tell me whether you already have it?</p>
</blockquote>
<h4 id="heading-defaultifemptyhttpreactivexiodocumentationoperatorsdefaultoremptyhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/defaultorempty.html">DefaultIfEmpty</a></h4>
<blockquote>
<p>When you have nothing to emit, here’s a default value that you can send back.</p>
</blockquote>
<h4 id="heading-sequenceequalhttpreactivexiodocumentationoperatorssequenceequalhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/sequenceequal.html">SequenceEqual</a></h4>
<blockquote>
<p>Here are two observables. Return true if their items (and their sequence) are the same.</p>
</blockquote>
<h4 id="heading-skipuntilhttpreactivexiodocumentationoperatorsskipuntilhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/skipuntil.html">SkipUntil</a></h4>
<blockquote>
<p>Here are two observables. Skip the items of the first one until the second one starts emitting.</p>
</blockquote>
<h4 id="heading-skipwhilehttpreactivexiodocumentationoperatorsskipwhilehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/skipwhile.html">SkipWhile</a></h4>
<blockquote>
<p>I give you a condition. You emit items until that condition becomes false.</p>
</blockquote>
<h4 id="heading-takeuntilhttpreactivexiodocumentationoperatorstakeuntilhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/takeuntil.html">TakeUntil</a></h4>
<blockquote>
<p>Here are two observables. Only give me the items of the first one until the second one starts emitting.</p>
</blockquote>
<h3 id="heading-mathematical-operators">Mathematical Operators</h3>
<h4 id="heading-averagehttpreactivexiodocumentationoperatorsaveragehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/average.html">Average</a></h4>
<blockquote>
<p>Give me an average of your Integer items.</p>
</blockquote>
<h4 id="heading-counthttpreactivexiodocumentationoperatorscounthtml"><a target="_blank" href="http://reactivex.io/documentation/operators/count.html">Count</a></h4>
<blockquote>
<p>Give me a count of your items.</p>
</blockquote>
<h4 id="heading-maxhttpreactivexiodocumentationoperatorsmaxhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/max.html">Max</a></h4>
<blockquote>
<p>Emit only the maximum-valued item.</p>
</blockquote>
<h4 id="heading-minhttpreactivexiodocumentationoperatorsminhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/min.html">Min</a></h4>
<blockquote>
<p>Emit only the minimum-valued item.</p>
</blockquote>
<h4 id="heading-reducehttpreactivexiodocumentationoperatorsreducehtml"><a target="_blank" href="http://reactivex.io/documentation/operators/reduce.html">Reduce</a></h4>
<blockquote>
<p>Do a scan, but only emit the final value.</p>
</blockquote>
<h4 id="heading-sumhttpreactivexiodocumentationoperatorssumhtml"><a target="_blank" href="http://reactivex.io/documentation/operators/sum.html">Sum</a></h4>
<blockquote>
<p>Return the sum of all your items.</p>
</blockquote>
<h3 id="heading-conversion-operators">Conversion Operators</h3>
<h4 id="heading-tohttpreactivexiodocumentationoperatorstohtml"><a target="_blank" href="http://reactivex.io/documentation/operators/to.html">To</a></h4>
<blockquote>
<p>Convert an observable into a List, Map or Array, or whatever I tell you to.</p>
</blockquote>
<p>That’s it for now. There are other operators as well, which you can find <a target="_blank" href="http://reactivex.io/documentation/operators.html">here</a>. You can also check out <a target="_blank" href="http://rxmarbles.com">RxMarbles</a>, which has cool diagrams for demonstrating each operator.</p>
<p>Anyway, thank you for reading. I hope the article helped you better understand what each of these commands does in a fun way.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Descartes, Berkeley and Functional Reactive Programming ]]>
                </title>
                <description>
                    <![CDATA[ By David Valdman Functional reactive programming is laden with unfamiliar terminology to the newcomer: pure functions, immutability, monads, etc. But beneath these concepts is a deeper principle — one debated long before Charles Babbage and the first... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/descartes-berkeley-and-functional-reactive-programming-18b0b61eac58/</link>
                <guid isPermaLink="false">66c349038cfe41ff707fbe31</guid>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Philosophy ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 07 Sep 2016 13:46:42 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*eZcgzUUKk-PnETNqIXMfcw.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By David Valdman</p>
<p>Functional reactive programming is laden with unfamiliar terminology to the newcomer: pure functions, immutability, monads, etc. But beneath these concepts is a deeper principle — one debated long before Charles Babbage and the first computers. I argue the difference between object-oriented programming (OOP) and functional reactive programming (FRP) is as much about interpretations of reality as it is about structures of programs.</p>
<p>Here’s a thought experiment we’ve all likely heard:</p>
<blockquote>
<p>If a tree falls in the middle of a forest, and no one is there to hear it, does it make a sound?</p>
</blockquote>
<p>There are many of ways to attack this question as ill-posed. Ignoring them for the moment, this question is poking at a fundamental aspect of reality: causality. Is existence dependent on, or independent of, observation? Let’s translate this thought experiment into code. Here’s a <strong><em>tree</em></strong>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> </span>{     <span class="hljs-keyword">constructor</span>(){         <span class="hljs-built_in">this</span>._fell = <span class="hljs-literal">false</span>;     }     <span class="hljs-keyword">set</span> <span class="hljs-title">fell</span>(<span class="hljs-params">state</span>){         <span class="hljs-built_in">this</span>._fell = state;     }     <span class="hljs-keyword">get</span> <span class="hljs-title">fell</span>(){         <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._fell;     }}
</code></pre><pre><code><span class="hljs-keyword">var</span> tree = <span class="hljs-keyword">new</span> Tree();tree.fell = <span class="hljs-literal">true</span>;
</code></pre><p>To make the <strong><em>tree</em></strong> fall we set its fallen state to <strong><em>true</em></strong>. This is textbook object-oriented programming. Its patterns are getters, setters, and state. Simple enough, but in the context of our thought experiment there is a lurking interpretation: if one questions whether the tree fell, even if they didn’t observe it, the answer is a resounding “<em>Yes!</em>” One only needs to check that <strong><em>tree.fell</em></strong> is <strong>true</strong>. Those that answer <em>yes</em> to our philosophical question do so because they can return to the forest, see the fallen tree, and deduce it fell in the past. Here is the codified equivalent. Looks like we’ve solved that centuries-old riddle.</p>
<p>Not so fast! Let’s look at a different approach. Here’s another <strong><em>tree</em></strong>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{}<span class="hljs-keyword">var</span> tree = <span class="hljs-keyword">new</span> Tree();tree.emit(<span class="hljs-string">'fall'</span>);
</code></pre><p>This is the “reactive” <strong><em>tree</em></strong>. Its patterns are events and transforms. In its purest form our tree maintains no state. We make it fall by broadcasting a <strong><em>fall</em></strong> event. Alas, the message falls on deaf ears! No state has changed, no evidence is left. There is no way to deduce the past by querying reality. Did the tree fall? <em><em>shrug</em></em></p>
<h3 id="heading-descartes-and-berkeley">Descartes and Berkeley</h3>
<p>The object-oriented and reactive approaches give two different answers to our thought experiment because they embody two contradictory philosophies of epistemology: Rationalism, popularized by Descartes in the late 1600s, and Empiricism popularized by Berkeley in the early 1700s.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1w0HHnALKtOg8UIL9dyDfrziVVwwfTj7f2eh" alt="Image" width="728" height="200" loading="lazy">
<em>Descartes takes as a short break from writing a Java interface</em></p>
<p>Descartes, in a streak of fanatical skepticism, found he could only be sure of one thing: his own existence. He came to this conclusion because he couldn’t doubt the existence of his thoughts and concluded there must be some entity doing the thinking, thus coining the phrase, <em>cogito ergo sum</em>: I think therefore I am. In other words: by acknowledging that there is some internal state that is changing, there must be some agent for whom the state belongs. To Descartes, changes of state is proof of existence — just like our first <strong><em>tree.</em></strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9jQ6H6ZLd-xgha0AWrT7PfFvfickuVBakznO" alt="Image" width="728" height="200" loading="lazy">
<em>Berkeley seen pondering Haskell type definitions</em></p>
<p>Soon after Descartes comes George Berkeley. Berkeley denounced the realist’s view. To Berkeley, it made no sense for material objects, like trees, to have existence. Existence only comes to us through thoughts (mental as opposed to physical experience), and thoughts must assimilate in the mind to exist. Material objects are deceptions; their essence is not their physicality but their ability to transform the immaterial. If a thought is not assimilated in the mind, it has no existence. Thus he popularized the Latin phrase <em>esse percepi</em>: to be is to be perceived.</p>
<p>Let’s translate Berkeley’s reality into code. For our second <strong><em>tree</em></strong> to make a sound a mind must interpret it. We will create a chain of causality, starting from the tree falling, to the air vibrating, to the ear creating an electrical stimulus, to the brain interpreting it as sound.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/XlaPm5rC3NWvz16x-OUYLTNSJF40VjosKvlC" alt="Image" width="800" height="200" loading="lazy"></p>
<p>When the tree falls, the air vibrates.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Air</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{    <span class="hljs-keyword">constructor</span> (){        <span class="hljs-built_in">super</span>();                <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mapFall</span> (<span class="hljs-params">fall</span>)</span>{...}        <span class="hljs-built_in">this</span>.on(<span class="hljs-string">'fall'</span>, <span class="hljs-function">(<span class="hljs-params">fall</span>) =&gt;</span> {            <span class="hljs-keyword">var</span> vibration = mapFall(fall);            <span class="hljs-built_in">this</span>.emit(<span class="hljs-string">'vibrate'</span>, vibration);        };    }}
</code></pre><p>When the air vibrates, the ear converts it to an electrical stimulus.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Ear</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{    <span class="hljs-keyword">constructor</span> (){         <span class="hljs-built_in">super</span>();                <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mapFrequency</span> (<span class="hljs-params">frequency</span>)</span>{...}        <span class="hljs-built_in">this</span>.on(<span class="hljs-string">'vibrate'</span>, <span class="hljs-function">(<span class="hljs-params">frequency</span>) =&gt;</span> {            <span class="hljs-keyword">var</span> stimulus = mapFrequency(frequency);            <span class="hljs-built_in">this</span>.emit(<span class="hljs-string">'stimulus'</span>, stimulus);        };    }}
</code></pre><p>When ear creates a stimulus, the brain interprets it as sound.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Brain</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{    <span class="hljs-keyword">constructor</span> (){        <span class="hljs-built_in">super</span>();        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mapStimulus</span> (<span class="hljs-params">signal</span>)</span>{...}        <span class="hljs-built_in">this</span>.on(<span class="hljs-string">'stimulus'</span>, <span class="hljs-function">(<span class="hljs-params">signal</span>) =&gt;</span> {            <span class="hljs-keyword">var</span> sound = mapStimulus(signal);            <span class="hljs-built_in">this</span>.emit(<span class="hljs-string">'sound'</span>, sound);        };    }}
</code></pre><p>We have effectively set up a chain of causality, which we make explicit by building a pipeline:</p>
<pre><code>tree.pipe(air).pipe(ear).pipe(brain);
</code></pre><p>Now, when the tree falls it makes an impression on a mind:</p>
<pre><code>brain.on(<span class="hljs-string">'sound'</span>, <span class="hljs-function">(<span class="hljs-params">sound</span>) =&gt;</span> {    <span class="hljs-comment">// We exit the system. You have been heard!    console.log(sound); });</span>
</code></pre><pre><code>tree.emit(<span class="hljs-string">'fall'</span>, fallData);
</code></pre><p>Berkeley called this concept <em>Subjective Idealism</em>. <em>Idealism</em> because it asserts only thoughts or ideas exist, and <em>subjective</em> because reality is dependent on the subjects that perceive it. In my opinion, Subjective Idealism is the philosophy underpinning reactive programming. Berkeley writes,</p>
<blockquote>
<p>It is indeed an opinion strangely prevailing amongst men, that houses, mountains, rivers, and in a word all sensible objects have an existence natural or real, distinct from their being perceived by the understanding. …For what are the fore-mentioned objects but the things we perceive by sense…and is it not plainly repugnant that any one of these or any combination of them should exist unperceived?</p>
</blockquote>
<p>I love this quote for its self-assured audacity. Berkeley is essentially calling us crazy for thinking that houses, mountains and rivers exist. In our example, trees, air, ears and brains are false idols; the only reality is <strong><em>mapFall</em></strong>, <strong><em>mapFrequency</em></strong> and <strong><em>mapStimulus</em></strong>. Reality is then never consumed, as it is with objects when they retain state. Reality is merely transformed.</p>
<h3 id="heading-subjective-idealism-in-practice"><em>Subjective Idealism</em> in Practice</h3>
<p>In OOP we create objects that encapsulate some kind of behavior. We then construct programs which are networked relationships of these objects. Our program is structurally a <em>graph</em>.</p>
<p>In FRP we create pipelines of functions that encapsulate causal relationships. Pipelines are then merged and branched to give the graph-like structure of an object-oriented program. However, there is an important limitation on the types of functions. Only <a target="_blank" href="https://en.wikipedia.org/wiki/Pure_function">pure functions</a> are allowed. That is, functions that cannot effect anything outside themselves. In our example, the <strong>Ear</strong> object cannot change how the <strong>Air</strong> object vibrated. This constraint ensures that our pipelines have a well-defined direction from cause to effect. In terms of structure, this means our program is a <a target="_blank" href="https://en.wikipedia.org/wiki/Directed_acyclic_graph"><em>directed acyclic graph</em></a> (DAG).</p>
<p>To reason about software, we must think of it as a sequence of causal relationships. We must be able to <em>order</em> the program. Mathematically, a graph can be <a target="_blank" href="https://en.wikipedia.org/wiki/Topological_sorting">ordered</a> if and only if it is a DAG. This is true no matter how you write your program. Whether you choose OOP, FRP or XYZ. What’s special about FRP, though, is that ordering is enforced by the pattern.</p>
<p>In OOP, ordering is left unspecified. Objects can call methods on other objects. Objects can change the state of other objects. Everything has read and write privileges by default. Specifying an order is done manually by the developer. It is up to them to relate the sequential ordering of lines in a program to an ordering of the objects’ causal relationships.</p>
<p>Unfortunately, this is all too easy to mess up. Notice that in OOP, when two objects write to the same shared state, you have a race condition. In FRP, when two functions try to affect one another you have an infinite loop. This is but one example of a theoretical pattern enforcing a practical result.</p>
<p>The bottom line is that it is not enough to encapsulate state. A well-written program will also encapsulate dependency.</p>
<h3 id="heading-tradeoffs"><strong>Tradeoffs</strong></h3>
<blockquote>
<p>“Programmers know the benefits of everything and the tradeoffs of nothing.”— Rich Hickey</p>
</blockquote>
<p>You’d think after all this FRP praising and OOP bashing, I’d be firmly in the FRP camp. You’d be wrong! FRP is a programming pattern, and patterns serve to constrain solutions. If the ideal solution doesn’t satisfy the constraints, you’ll be wasting energy fighting against the pattern.</p>
<p>To be concrete, there are a few simple annoyances of FRP. Take immutability — you are always creating more memory. You can never, say, sort a list in place. You will always be creating a new list. In theory, immutability is a good pattern to observe. In practice, you may be memory constrained, and it may be a good idea to swim against the FRP current.</p>
<p>But this is not <em>the</em> glaring problem. The glaring problem is that FRP becomes an anti-pattern when you don’t know when two parts of a codebase will interact. Take, for example, a first person shooter game. Somewhere is a <strong>bullet</strong> object, and somewhere else is a <strong>player</strong> object. A bullet may hit a player, but it’s unclear when this will happen. These objects need to retain state (velocity of the bullet, health of the player, etc.) so it is available at the moment they interact. Perhaps in the abstract the entire game can be thought of as one causal pipeline, but that sounds more daunting to me than thinking in terms of decoupled objects and state.</p>
<p>To put on my philosophical hat once more, physics may decree that reality is one causal pipeline whose time evolution is governed by deterministic physical laws, and whose initial conditions (or probabilities) are provided by the big bang. But this is hardly how humans reason about cause and effect. We naturally slice up reality into higher-level objects and reason about their inter-relations. It can be simpler that way, even though it’s error prone!</p>
<p>I feel this is why FRP hasn’t been been wholly embraced by the programming community, even after seeing its many advantages. The best we should hope for when writing programs is to use FRP principles in places where its patterns fit the solution, and let them inspire OOP patterns where its patterns do not. To me this is a distinction between solutions that can be thought of as pipelines, and solutions that shouldn’t be.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In philosophy the objective is not to solve our deepest problems, but to have a shared language and historical precedent to debate them. So when a new problem emerges, we don’t have to start over. Similarly for programming patterns. They are not used to decide right and wrong, as if these concepts have universal appeal. They are used to classify problems and their approaches.</p>
<p>We should also look to other disciplines, much older than computer science, to see whether their shared language and historical precedent can inspire our own. Then we may see that the question, “<em>did the tree fall?</em>” is not answered with a <em>yes</em> or a <em>no</em>. That instead it questions a perspective. One that can frame our philosophy of epistemology or our architecture of programs. And one to which the answer lies between a state of mind, and a flow of thought!</p>
<p><strong>Preview of Part II</strong></p>
<p>There is still a nagging dilemma in our thought experiment. Even if there are no people to experience the sound, surely when the tree falls the air must vibrate! Right? In Part II we will go further down the rabbit hole to see that FRP can give a surprising interpretation here too. We’ll think of data flows in terms of push vs pull and see how this appears in concepts like lazy evaluation, algorithms like ray tracing, and applications like Excel.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
