<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Xinzhuo Liu on Medium]]></title>
        <description><![CDATA[Stories by Xinzhuo Liu on Medium]]></description>
        <link>https://medium.com/@xinzhuo.liu?source=rss-a2e9fdda5829------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dwryRwFXgXGpjPFh.</url>
            <title>Stories by Xinzhuo Liu on Medium</title>
            <link>https://medium.com/@xinzhuo.liu?source=rss-a2e9fdda5829------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:43:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xinzhuo.liu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ngrx: Reactive Extensions for Angular]]></title>
            <link>https://medium.com/@xinzhuo.liu/ngrx-reactive-extensions-for-angular-39965c9b13d3?source=rss-a2e9fdda5829------2</link>
            <guid isPermaLink="false">https://medium.com/p/39965c9b13d3</guid>
            <category><![CDATA[ngrx]]></category>
            <dc:creator><![CDATA[Xinzhuo Liu]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 08:25:24 GMT</pubDate>
            <atom:updated>2017-12-20T08:25:24.153Z</atom:updated>
            <content:encoded><![CDATA[<p>As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state（eg. server responses, cached data, created data, URL and router, client state, transient client state and so on） than ever before.</p><p>Ngrx is one choice to do it, there are still some other extension for Angular such as angular-redux.</p><p>3 <strong>Principles of redux:</strong></p><p>Redux can be described in three fundamental principles:</p><ul><li>Single souce of truth: the state of your whole application is stored in an object tree within a single store.</li><li>State is read only: the only way to change the state is to emit an action, an object describing what happened.</li><li>Changes are made with pure function: to specify how the state tree is transformed by actions, you write pure reducers.</li></ul><p><strong>Without Ngrx:</strong></p><p>In angular, component need to get data from service, and the cached data will also store in service. With the developing process the relationship between components and services will be hard to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*piPv6ZPx5FGlQwWbAuzufA.png" /><figcaption>Without Ngrx</figcaption></figure><p><strong>Action:</strong></p><p>Actions are information payloads that send data from the application to the reducer, which updates the store. Actions are the only way the store receives data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*FadaalzijBhAa0KqL-0S3A.png" /><figcaption>Action</figcaption></figure><p>In action there is only one field called type, which is a unique identifier. Payload is defined in the constructor of an action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*3zZE7ArMicVScszfv_MM7Q.png" /><figcaption>Action definition</figcaption></figure><p><strong>Reducer:</strong></p><p>Reducers specify how the state changes in response to actions. A reducer is a pure function that describes state mutations in the app by taking the previous state and the dispatched action and returning the next state as a new object, generally using Object.assign and/or spread syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*vY6ErTezTqS2taR3GtV7sw.png" /><figcaption>Reducer</figcaption></figure><p><strong>Ngrx/Store:</strong></p><p>ngrx/store is a controlled state container designed to help write performant, consistent applications on top of Angular. Core tenets:</p><ul><li>State is a single immutable data structure</li><li>Actions describe state changes</li><li>Pure functions called reducers take the previous state and the next action to compute the new state</li><li>State accessed with the Store, an observable of state and an observer of actions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMEltQC8xd7KJnLe1xHUEw.png" /><figcaption>Angular with Ngrx/Store</figcaption></figure><p>After combining with Ngrx/store, the working way is:</p><ol><li>Component dispatch action.</li><li>Reducer will update ths states in Store.</li><li>Component will get selected states from Store and pass it to the view by async pipeline.</li></ol><p>In this way the data flows from component to reducer, effecting the Store states, and then subscribed by component and pass to view. This flow is one-way direction and meet with the 3 principles. But the relationship between component and service is still not improved.</p><p><strong>Ngrx/Effect:</strong></p><p>ngrx/effects provides an API to model event sources as actions. Effects:</p><ul><li>Listen for actions dispatched from @ngrx/store</li><li>Isolate side effects from components, allowing for more <em>pure</em> components that select state and dispatch actions</li><li>Provide new sources of actions to reduce state based on external interactions such as network requests, web socket messages and time-based events.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEJRtHVNo8qlHLS8LT0hEA.png" /><figcaption>Angular with ngrx/Effect</figcaption></figure><p>After combining with ngrx/Effect, the working flow changed. After component dispatch an action, there is a side-effect binding with this process, ngrx/Effect will identify this action based on action type and then invoke the service to get data or do some operations. After this process, effect will dispatch a new Action.</p><p>During thie work flow, because all the states changing is based on actions, the whole process will be recorded by ngrx, including states changing, action, response. The relationship between component and service can be decoupled. In addition, there is no directive relationship between effect and component, so the whole http request process can be changed flexible and tracable.</p><p><strong>Benefits:</strong></p><p>Acording to these analysis, the benefits of ngrx are:</p><ul><li>Remembering each page’s state and user’s operation.</li><li>Rehydrating the states from local storage.</li><li>Recording the whole process of status changing, which can help to debugging, store and recovery page’s state or user’s operation.</li><li>Getting data with async process, reduce the burden of server.</li><li>Decoupling component and service, program more flexible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39965c9b13d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular and Rxjs]]></title>
            <link>https://medium.com/@xinzhuo.liu/angular-and-rxjs-34be378c15ec?source=rss-a2e9fdda5829------2</link>
            <guid isPermaLink="false">https://medium.com/p/34be378c15ec</guid>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Xinzhuo Liu]]></dc:creator>
            <pubDate>Mon, 18 Dec 2017 15:35:04 GMT</pubDate>
            <atom:updated>2017-12-18T15:35:04.589Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular:</p><p>Angular is a framework for building client applications in HTML and either JavaScript or a language like TypeScript that compiles to JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MiKpQhapQqGl7uuf.png" /><figcaption>Angular Architecture</figcaption></figure><ol><li>Module</li></ol><p>Angular apps are modular and Angular has its own modularity system called <em>NgModules</em>. Every Angular app has at least one NgModule class, <a href="https://angular.io/guide/bootstrapping">the <em>root module</em></a>, conventionally named AppModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*OMODUAI4iovSW9ZvaZwW_g.png" /><figcaption>AppModule</figcaption></figure><p><a href="https://angular.io/api/core/NgModule">NgModule</a> is a decorator function that takes a single metadata object whose properties describe the module. The most important properties are:</p><ul><li>declarations - the <em>view classes</em> that belong to this module. Angular has three kinds of view classes: <a href="https://angular.io/guide/architecture#components">components</a>, <a href="https://angular.io/guide/architecture#directives">directives</a>, and <a href="https://angular.io/guide/pipes">pipes</a>.</li><li>exports - the subset of declarations that should be visible and usable in the component <a href="https://angular.io/guide/architecture#templates">templates</a> of other modules.</li><li>imports - other modules whose exported classes are needed by component templates declared in <em>this</em> module.</li><li>providers - creators of <a href="https://angular.io/guide/architecture#services">services</a> that this module contributes to the global collection of services; they become accessible in all parts of the app.</li><li>bootstrap - the main application view, called the <em>root component</em>, that hosts all other app views. Only the <em>root module</em> should set this bootstrap property.</li></ul><p>2. Component</p><p>Component is function, decorator by key word <em>“@Component”</em>, and metadata contains: CSS selector, HTML Template, CSS styles(optional).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJ1FSJAm7VI14A_q-i2q6Q.png" /><figcaption>Component</figcaption></figure><p>2.1 Metadata</p><p>In this example, the code between “{…}” is a meta data object. Metadata tells Angular how to process a class.</p><p>Here are a few of the most useful @<a href="https://angular.io/api/core/Component">Component</a> configuration options:</p><ul><li>selector: CSS selector that tells Angular to create and insert an instance of this component where it finds a &lt;hero-list&gt; tag in <em>parent</em> HTML. For example, if an app&#39;s HTML contains &lt;hero-list&gt;&lt;/hero-list&gt;, then Angular inserts an instance of the HeroListComponent view between those tags.</li><li>templateUrl: module-relative address of this component&#39;s HTML template, shown <a href="https://angular.io/guide/architecture#templates">above</a>.</li><li>providers: array of dependency injection providers for services that the component requires. This is one way to tell Angular that the component&#39;s constructor requires a HeroService so it can get the list of heroes to display.</li></ul><p>When we want to access other components, we can just use CSS selector to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*68dsVMCB6bnGlVyCAIWo9Q.png" /><figcaption>Access other components</figcaption></figure><p>2.2 Data Binding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0BhQJVJ9UYtiz18yAGKTw.png" /><figcaption>Data binding</figcaption></figure><p>2.3 Life Cycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Es-lZdZODu7r9DaQ3eHCmA.png" /><figcaption>Component life cycle</figcaption></figure><p>3. Dependency Injection</p><p><em>Dependency injection</em> is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*9p-gytUCQDfxZFIQsnmvPA.png" /><figcaption>Service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*a83d7OcuYLI8x3rm0GB5KQ.png" /><figcaption>Component</figcaption></figure><p>The injector relies on providers to create instances of the services that the injector injects into components and other services.</p><p>When a component at the bottom requests a dependency, Angular tries to satisfy that dependency with a provider registered in that component’s own injector. If the component’s injector lacks the provider, it passes the request up to its parent component’s injector. If that injector can’t satisfy the request, it passes it along to its parent component’s injector. The requests keep bubbling up until we find an injector that can handle the request or run out of component ancestors. If we run out of ancestors, Angular throws an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bhAPtDLot_Ci-3V02GEWA.png" /><figcaption>Dependency Injection</figcaption></figure><p>Rxjs:</p><ol><li>Every thing is a stream.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*xzuR11jdz7hU08Us.png" /><figcaption>streams</figcaption></figure><p>Front end developing is different from backend developing. The mind of it is ‘everything is a stream’. It was because every operation from a user can be seen as a data of a stream. In this way it’s easier to handle these data. For example in an FPS game, it’s hard to do the data statics. Questions such as ‘how many shot in one game?’, ‘what’s the hit rate of a player?’ are pretty hard to handle in the traditional design. But using stream can hanld these problems well. A stream is simply a collection that arrives over time. Reactive programming is programming with asynchronous data streams. RxJS is one of the hottest libraries in web development for reactive programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*HjmhpDU2sodqe2SS.jpeg" /><figcaption>Every thing is a stream</figcaption></figure><p>2. Observable</p><p>In RxJS, you represent asynchronous data streams using observable sequences or also just called observables. Observables are very flexible and can be used using push or pull patterns. In JavaScript we may distinguish between three of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*uFCKShRyqxOqESyE.png" /><figcaption>Generator, Observable, Function, Promis</figcaption></figure><p><strong>Promises:</strong> for returning single asynchronous results,<br><strong>Functions:</strong> for single results, and<br><strong>Generators</strong>: for providing iterators.</p><p>3. Subject</p><p>Observable is a data pro­ducer. Subject is not only a data pro­ducer but also a data consumer. There are 3 different kinds of Subject:</p><ul><li>BehaviorSubject: One of the variants of Subjects is the BehaviorSubject, which has a notion of &quot;the current value&quot;. It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the &quot;current value&quot; from the BehaviorSubject.</li><li>ReplaySubject: The ReplaySubject subclass of Subject is like BehaviorSubject in that it can send old values to new incoming subscribers, but it in general is able to <em>record</em> a part of the Observable execution.</li><li>AsyncSubject: The AsyncSubject is a variant where only the last value of the Observable execution is sent to its observers, and only when the execution completes.</li></ul><p>4. Rxjs Operations</p><ul><li>Creating Observables: Operators that originate new Observables.</li><li>Transforming Observables: Operators that transform items that are emitted by an Observable.</li><li>Filtering Observables: Operators that selectively emit items from a source Observable.</li><li>Combining Observables: Operators that work with multiple source Observables to create a single Observable</li><li>Error Handling Operators: Operators that help to recover from error notifications from an Observable</li><li>Observable Utility Operators: A toolbox of useful Operators for working with Observables</li><li>Conditional and Boolean Operators: Operators that evaluate one or more Observables or items emitted by Observables</li><li>Mathematical and Aggregate Operators: Operators that operate on the entire sequence of items emitted by an Observable</li><li>Backpressure Operators: strategies for coping with Observables that produce items more rapidly than their observers consume them<br>Connectable Observable Operators: Specialty Observables that have more precisely-controlled subscription dynamics</li><li>Operators to Convert Observables: Convert an Observable into another object or data structure</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34be378c15ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Reactive Programming]]></title>
            <link>https://medium.com/@xinzhuo.liu/functional-reactive-programming-e341a52e40aa?source=rss-a2e9fdda5829------2</link>
            <guid isPermaLink="false">https://medium.com/p/e341a52e40aa</guid>
            <category><![CDATA[reactive-promming]]></category>
            <category><![CDATA[reactivex]]></category>
            <dc:creator><![CDATA[Xinzhuo Liu]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 18:14:03 GMT</pubDate>
            <atom:updated>2017-03-26T18:14:03.705Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>What is Functional Reactive Programming</strong></li></ol><p><strong>Functional reactive programming</strong> (FRP) is a <strong>programming</strong> paradigm for <strong>reactive programming</strong> (asynchronous data flow <strong>programming</strong>) using the building blocks of <strong>functional programming</strong> (e.g. map, reduce, filter).</p><p>As I see, it’s just a combination of Observer Pattern(data streams publish and subscribe) and Iterator Pattern(single data stream). Observables are really cool, because they fill the gap by being the ideal way to access asynchronous sequences of multiple items.</p><p>Now let’s come back to stream, starting with our familiar “clicks on a button” event stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*pUwd-zd-p-nsgncT9VtVxw.png" /><figcaption>Clicks on A Button</figcaption></figure><p>A stream is a sequence of ongoing events ordered in time. It can emit three different things: a value (of some type), an error, or a “completed” signal. We capture these emitted events only asynchronously, by defining a function that will execute when a value is emitted, another function when an error is emitted, and another function when ‘completed’ is emitted.</p><p><strong>2. How powerful it is.</strong></p><p>Here are 2 examples to show how powerful FRP is:</p><p>2.1 Update b based on a</p><p>Here is the tradationa way, what happend is that every time if we update the value of a, we need to modify the value of b manully.</p><pre>// JavaScript<br>// proactive<br>var obj = {<br>  a: 0,<br>  b: 1<br>};<br><br>obj.a = 3;<br>obj.b = obj.a + 1;  // proactive<br>console.log(obj.b); // b = 4</pre><p>But for FRP, things become easier, just observe the change of a.</p><pre>// JavaScript<br>// reactive<br>Object.observe(obj, function (changes){<br>  obj.b = changes[0].object.a + 1;<br>});<br><br>obj.a = 5;<br>console.log(obj.b); // 6</pre><p>Maybe you still prefer the tradition way, but let’s see the second example, and see the amazing FRP.</p><p>2.2 Query GitHub’s API to first get a list of users, and then request the details for each user.</p><p>Old Style, It calls to the web service, uses a callbacks interface to pass the successful result to the next web service call, define another success callback, and then moves on to the next web service request. As you can see, this results in two nested callbacks:</p><pre><em>//The &quot;Nested Callbacks&quot; Way</em><br><strong>public</strong> <strong>void</strong> <strong>fetchUserDetails()</strong> <br><strong>{</strong><br><em>//first, request the users...</em><br>mService<strong>.</strong>requestUsers<strong>(new</strong> Callback<strong>&lt;</strong>GithubUsersResponse<strong>&gt;() {</strong><br>@Override<br><strong>public</strong> <strong>void</strong> <strong>success(final</strong> GithubUsersResponse githubUsersResponse<strong>,</strong><br><strong>final</strong> Response response<strong>) {</strong><br>    Timber<strong>.</strong>i<strong>(</strong>TAG<strong>,</strong> &quot;Request Users request completed&quot;<strong>);</strong><br>    <strong>final</strong> List<strong>&lt;</strong>GithubUserDetail<strong>&gt;</strong> githubUserDetails <strong>=</strong> <strong>new</strong>        ArrayList<strong>&lt;</strong>GithubUserDetail<strong>&gt;();</strong><br>    <em>//next, loop over each item in the response</em><br>    <strong>for</strong> <strong>(</strong>GithubUserDetail githubUserDetail <strong>:</strong> githubUsersResponse<strong>) {</strong><br>        <em>//request a detail object for that user</em><br>        mService<strong>.</strong>requestUserDetails<strong>(</strong>githubUserDetail<strong>.</strong>mLogin<strong>,</strong><br>        Callback<strong>&lt;</strong>GithubUserDetail<strong>&gt;() {</strong><br>        @Override<br>        <strong>public</strong> <strong>void</strong> <strong>success(</strong>GithubUserDetail githubUserDetail<strong>,</strong>Response response<strong>)<br>        {</strong><br>        Log<strong>.</strong>i<strong>(</strong>&quot;User Detail request completed for user : &quot; <strong>+</strong> githubUserDetail<strong>.</strong>mLogin<strong>);</strong><br>        githubUserDetails<strong>.</strong>add<strong>(</strong>githubUserDetail<strong>);</strong><br>        <strong>if</strong> <strong>(</strong>githubUserDetails<strong>.</strong>size<strong>()</strong> <strong>==</strong> githubUsersResponse<strong>.</strong>mGithubUsers<strong>.</strong>size<strong>()) {</strong><br>        <em>//we&#39;ve downloaded&#39;em all - notify all who are interested!</em><br>        mBus<strong>.</strong>post<strong>(new</strong> UserDetailsLoadedCompleteEvent<strong>(</strong>githubUserDetails<strong>));</strong><br>        <strong>}</strong><br>    <strong>}</strong><br><br>    @Override<br>    <strong>public</strong> <strong>void</strong> <strong>failure(</strong>RetrofitError error<strong>)</strong> <strong>{</strong><br>    Log<strong>.</strong>e<strong>(</strong>TAG<strong>,</strong> &quot;Request User Detail Failed!!!!&quot;<strong>,</strong> error<strong>);</strong><br>    <strong>}</strong><br>  <strong>});</strong><br><strong>}</strong><br><strong>}</strong><br><br>    @Override<br>    <strong>public</strong> <strong>void</strong> <strong>failure(</strong>RetrofitError error<strong>)</strong> <strong>{</strong><br>                Log<strong>.</strong>e<strong>(</strong>TAG<strong>,</strong> &quot;Request User Failed!!!!&quot;<strong>,</strong> error<strong>);</strong><br>            <strong>}</strong><br>        <strong>});</strong><br>    <strong>}</strong></pre><p>FPR style, they have total the same functions:</p><pre><strong>public</strong> <strong>void</strong> <strong>rxFetchUserDetails()</strong> <strong>{</strong><br>        <em>//request the users</em><br>        mService<strong>.</strong>rxRequestUsers<strong>().</strong>concatMap<strong>(</strong>Observable:<strong>:</strong>from<strong>)</strong><br>        <strong>.</strong>concatMap<strong>((</strong>GithubUser githubUser<strong>)</strong> <strong>-&gt;</strong><br>                        <em>//request the details for each user</em><br>                        mService<strong>.</strong>rxRequestUserDetails<strong>(</strong>githubUser<strong>.</strong>mLogin<strong>)</strong><br>        <strong>)</strong><br>        <em>//accumulate them as a list</em><br>        <strong>.</strong>toList<strong>()</strong><br>        <em>//define which threads information will be passed on</em><br>        <strong>.</strong>subscribeOn<strong>(</strong>Schedulers<strong>.</strong>newThread<strong>())</strong><br>        <strong>.</strong>observeOn<strong>(</strong>AndroidSchedulers<strong>.</strong>mainThread<strong>())</strong><br>        <em>//post them on an eventbus</em><br>        <strong>.</strong>subscribe<strong>(</strong>githubUserDetails <strong>-&gt;</strong> <strong>{</strong><br>            EventBus<strong>.</strong>getDefault<strong>().</strong>post<strong>(new</strong> UserDetailsLoadedCompleteEvent<strong>(</strong>githubUserDetails<strong>));</strong><br>        <strong>});</strong><br>    <strong>}</strong></pre><p><strong>3. Important Operators of ReactiveX</strong></p><p>After we know how powerful it is, then let’s see some important method of ReactiveX, an API for asynchronous programming with observable streams, which can help us to do the FRP.</p><p>3.1 Map</p><p>Map can help us to transform the items emitted by an Observable by applying a function to each item. eg: I have an array([1,2,3,4,5]) and I want to get [10,20,30,40,50] (x=&gt;x*10), than one line code can finish this task:</p><p>map(x =&gt; x * 10)</p><p>3.2 Switch</p><p>Switch can convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imhgbM9OrTg3fwWTqXTBwQ.png" /><figcaption>Switch</figcaption></figure><p>3.3 Subscribe</p><p>Subscribe is an operate upon the emissions and notifications from an Observable. The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator.</p><p>3.4 Catch and Retry</p><p>Catch can recover from an onError notification by continuing the sequence without error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3QzG2ydxfIQ5QpY8xXOpg.png" /><figcaption>Catch</figcaption></figure><p>Retry is much clear: if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKwFInT4L1PB4363Q5RPBw.png" /><figcaption>Retry</figcaption></figure><p>3.5 Debounce</p><p>Debounce only emit an item from an Observable if a particular timespan has passed without it emitting another item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*SZVZdnxruiApK2Qj27d3Zw.png" /><figcaption>Debounce</figcaption></figure><p><strong>4. A real example: A Search Bar</strong></p><p>If we want to build a search bar, we need to find out the requirement:</p><p>(1) This search bar will start search when user stop to type.</p><p>(2) If there is no letter input in the stream for 250 ms, we think this user stoping typing.</p><p>So the processes should be:</p><ol><li>Subscribe user’s typing</li><li>Using debounce as the filter, and find out the time to invoke the searching service.</li><li>Unpack the keywords</li><li>Set the minimum size of the keywords</li><li>Check if the keywords changed</li><li>Invoke the SearchService to Search</li><li>Get most-recently-emitted of those Observables(result)</li><li>Check response is not undefined</li><li>Handle Error</li></ol><p>And here is the code:</p><pre>var result = Rx.Observable.fromEvent(q, &#39;keyup&#39;)<br>               .debounce(300)<br>               .map(function (ev) { return ev.target.value; })<br>               .where(function (text) { return text.length &gt;= 3; })<br>               .distinctUntilChanged()<br>               .map(searchService)<br>               .switch()<br>               .where(function (obj) { return obj !== undefined; })<br>               .catch(handleError);</pre><p>Reference:</p><ol><li>The introduction to Reactive Programming you’ve been missing (<a href="http://twitter.com/andrestaltz">andrestaltz</a>) <a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">https://gist.github.com/staltz/868e7e9bc2a7b8c1f7504</a></li><li><a href="http://reactivex.io/intro.html">http://reactivex.io/intro.html</a></li></ol><p>3. Functional Reactive Programming 的入門心得 ( <a href="https://medium.com/@rayshih771012?source=post_header_lockup">Ray Shih</a>) <a href="https://medium.com/@rayshih771012/functional-reactive-programming-70be6bd8726b#.1hiphtd81">https://medium.com/@rayshih771012/functional-reactive-programming-70be6bd8726b#.1hiphtd81</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e341a52e40aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>