<?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 Sergey Dolin on Medium]]></title>
        <description><![CDATA[Stories by Sergey Dolin on Medium]]></description>
        <link>https://medium.com/@s4y.solutions?source=rss-486b6274650a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9yZ_i_Y9N9t-Y7cVIrCwdQ.jpeg</url>
            <title>Stories by Sergey Dolin on Medium</title>
            <link>https://medium.com/@s4y.solutions?source=rss-486b6274650a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:53:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s4y.solutions/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[ES Modules, Typescript and Mocha]]></title>
            <link>https://medium.com/@s4y.solutions/es-modules-typescript-and-mocha-9e6138883e57?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e6138883e57</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[mocha-js]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 18:12:12 GMT</pubDate>
            <atom:updated>2021-12-03T18:12:38.411Z</atom:updated>
            <content:encoded><![CDATA[<p>The problem we were solving was to test ESM “import/export” produced from the typescript codebase.</p><h3>The final configuration we came to</h3><h4>tsconfig.json</h4><p>Command the typescript compiler to produce JS code with “import/export” syntax</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>  }<br>}</pre><h4>package.json</h4><p>Tell the node that every file should be treated as “a module” and thus it is possible to use import within it</p><pre>{<br>   &quot;type&quot;:&quot;module&quot;,<br>}</pre><p>This way we get rid of <em>“SyntaxError: Cannot use import statement outside a module”</em> error but now must set .cjs extension for the every pure JS file which use require CommonJS syntax. In case there are lot of such JS files it is possible to remove ”type”:”module” option but rename the JS files with import directives to .mjs</p><pre>{<br>   &quot;scripts&quot;:{<br>      &quot;test&quot;: &quot;mocha -n=loader=ts-node/esm -n=es-module-specifier-resolution=node **/*.spec.ts&quot;<br>    }<br>}</pre><p>To run mocha is the most difficult to discovery and cumbersome task.</p><p>First we do not use ts-mocha or such, just pass some options to the node process the mocha is to be running in with the -n options. Pay attention the options are not mocha related.</p><p>-n=loader=ts-node/esm is equivalent of --loader ts-node/ems passed to the node and effectively does the precompilation of .ts files into js code before it can be executed by node.</p><blockquote>It is obvious that in order to have the ts-node available for the project you have to add the npm with npm install -D ts-node</blockquote><p>Because of &quot;module&quot;: &quot;ESNext&quot; setting in the tsconfig.json the produced JS code will have import/export directives which is not supposed to be understood by node by default. But it is if we tell all the JS files are “modules” by &quot;type&quot;=&quot;module&quot; in package.json</p><p>The above should be enough for the first sight but you definitely shall get the Error: Cannot find module ... for every file your try to import. The node team made this behaviour intentionally although their motivation is not clear. To make it to disappear another options is necesary:</p><pre>-n=es-module-specifier-resolution=node</pre><p>which is equivalent of node option --es-module-specifier-resolution=node</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e6138883e57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving average, Bollinger bands noise data filter]]></title>
            <link>https://medium.com/@s4y.solutions/moving-average-bollinger-bands-noise-data-filter-e089950070bb?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e089950070bb</guid>
            <category><![CDATA[kalman-filter]]></category>
            <category><![CDATA[itagone]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[itag]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 04:47:20 GMT</pubDate>
            <atom:updated>2021-07-05T17:14:10.321Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://play.google.com/store/apps/details?id=s4y.itag">iTagOne</a> we showed the RSSI signal strength from the very beginning but in fact the feature was absolutely useless as LEDs were jumping from red to green like crazy frogs.</p><p>The obvious solution to calm the sensor down is to apply the Kalman filter like we did for GPS sensor in <a href="https://play.google.com/store/apps/details?id=s4y.waytoday">WayToday</a> tracker, but… The filter is great but it assumes: there’s a physical low to predict the measurement, there’s knows sensor and environment variations and moreover the Kalman filter obey the control influence. Of course it is possible to replace the low with “to be const” and zeroing the variances. And what would be left from all that matrix algebra magic? Almost nothing.</p><p>So, finally we went the way the ancient financial speculates were done. First of let’s replace the last measurement with the average value of the few last measurements. The implementation of Moving Average filter is absolutely trivial.</p><pre>public class RSSIFilter {<br>    int[] measurements = {0, 0, 0, 0, 0, 0, 0};<br>    int current = 0;<br>    int length = 0;<br><br>    int average = 0;<br>    public void reset() {<br>        current = 0;<br>        length = 0;<br>        Arrays.<em>fill</em>(measurements, 0);<br>    }<br><br>    public void add(int rawmeasurement) {<br>        int measurement = rawmeasurement;<br>        measurements[current++] = measurement;<br>        if (current == measurements.length) {<br>            current = 0;<br>        }<br>        if (length &lt; measurements.length) {<br>            length++;<br>        }<br>        int sum = 0;<br>        for (int i = 0; i &lt; length; i++) {<br>            sum += measurements[i];<br>        }<br>        average = (int) ((double) sum / length + 0.5);<br>    }<br><br>    public int get() {<br>        return average;<br>    }<br>}</pre><p>And it already works pretty well — the gauge started to jump not more then 1–2 levels. Ok, but still annoying.</p><p>Besides the “close to real” value the RSSI sensor produces “spikes” which make great impact on the average while being “obviously” wrong.</p><p>In the human sense “obviously” is easy to see, but how to explain it to the mindless computer? Well, the math has the answer: standard deviation. Everything that differ from the average more than the predefined value is counted as wrong and might be skipped</p><pre>public void add(int rawmeasurement) {<br>        if (Math.abs(average-rawmeasurement) &gt; 20)<br>           return;</pre><p>Where a “20” came from and why “abs” instead of the famous square roots of square sums used in the statistic everywhere?</p><p>20 — was a result of some heuristic observation of the real iTag gadget connected to the real Samsung. We just run few hundreds sample measurement and calculated the average of “last measurement minus average of 5 last measurements”</p><p>The result become almost perfect. Even perfect without “almost”. The gauge now shows the signal strength absolutely smoothly and changed accordingly the distance from the phone to the tag.</p><p>So the skipping the spikes proved to be working solution. And as we do not have to care about math theory and we definitely will no calculate derivatives so we do not need the very expensive replacement of the modulo with square roots.</p><p>But once again there’s a “but…”. The magic value 20 worked for the specific iTag, specific Samsung and, possible, for specific distance. Would it work for anybody in any circumstance? Who knows. We do not.</p><p>And now another solution from financial market analytics tool — they used to use “Bollinger bands” for tens of years to detect the “unusual” price spikes.</p><pre>Ironically both MA and BB can not be used for financial markets in the direct way. They are statistic tools and assume they applied to the &quot;normal distributed data&quot;, but the market prices are not such data.</pre><pre>Even worse, the prices are sometimes close to the normal distribution and sometimes they are not. The experienced financial analytic sees (or feels) the difference, but the novices are lured to bring their money to the easy to predict normal distributed market (having narrow Bollinger band) and are loosing all the money in the next unpredictable (because of market has fractal math nature which does not obey statical laws) spike. </pre><p>Bollinger bands in fact is very simple tool as well. It is the same moving average of the difference between the last measurement and average of few last measurements.</p><p>So, while the measurements are close to each other the difference is pretty small and we will detect the spike absolutely obviously: “it differ too much from the expected difference”. But unlike the previous code the spike won’t be just thrown off. It will be added to the average difference and expand the band a bit. If the spike was sporadic the band will narrow back on the next measurements and we happily ignore the wrong valut. In contrast if the change of the value were real and correct, the band will continue to expand and soon the the measurements that differ from the average fall into the expanded band and are not skipped. This way we start to react on the changes much faster if we would just wait for the average changes.</p><p>In the specific application of the iTag which might be thrown away and thus it is expected to have the measurement changed very fast. We felt uneasy of waiting for BB expand though. And added the quirk code to assume “3 spikes in row are not spikes, but their average is the correct value”.</p><p>So here we end up with the real life code:<br><a href="https://github.com/s4ysolutions/itag/blob/master/itagble/src/main/java/s4y/itag/ble/RSSIFilter.java">https://github.com/s4ysolutions/itag/blob/master/itagble/src/main/java/s4y/itag/ble/RSSIFilter.java</a></p><pre>package s4y.itag.ble;<br><br>import java.util.Arrays;<br><br>public class RSSIFilter {<br>    int[] measurements = {0, 0, 0, 0, 0, 0, 0};<br>    int[] deviations = {0, 0, 0, 0, 0, 0, 0};<br>    int[] spikes = {0, 0, 0};<br>    int spikecount = 0;<br>    int current = 0;<br>    int length = 0;<br><br>    int average = 0;<br>    int deviation = 15;<br><br>    public void reset() {<br>        current = 0;<br>        length = 0;<br>        deviation = 15;<br>        Arrays.fill(measurements, 0);<br>        Arrays.fill(deviations, 0);<br>    }<br><br>    public void add(int rawmeasurement) {<br>        int measurement;<br>        if (average != 0 &amp;&amp; length &gt; 3 &amp;&amp; Math.abs(rawmeasurement - average) &gt; deviation) {<br>            spikes[spikecount++] = rawmeasurement;<br>            if (spikecount &lt; spikes.length) return;<br>            measurement = (spikes[0] + spikes[1] + spikes[2]) / 3;<br>        } else {<br>            measurement = rawmeasurement;<br>        }<br>        spikecount = 0;<br>        measurements[current++] = measurement;<br>        if (current == measurements.length) {<br>            current = 0;<br>        }<br>        if (length &lt; measurements.length) {<br>            length++;<br>        }<br>        int sum = 0;<br>        for (int i = 0; i &lt; length; i++) {<br>            sum += measurements[i];<br>        }<br>        average = (int) ((double) sum / length + 0.5);<br>        deviations[current] = Math.abs(average - rawmeasurement);<br><br>        int sumdeviations = 0;<br>        for (int i = 0; i &lt; length; i++) {<br>            sumdeviations += deviations[i];<br>        }<br>        deviation = (int) ((double) sumdeviations / length + 0.5);<br>    }<br><br>    public int get() {<br>        return average;<br>    }<br>}</pre><p>50 lines of code, less than an hour of worktime, no egg-heads math, the ways for improvement. Did not it worth to be developed instead of using Kalman?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e089950070bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The right way to cook react-hooks]]></title>
            <link>https://medium.com/@s4y.solutions/the-right-way-to-cook-react-hooks-d07c1434db6b?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d07c1434db6b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 07:27:29 GMT</pubDate>
            <atom:updated>2019-10-16T15:44:39.622Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://medium.com/@s4y.solutions/react-hooks-another-rotten-fruit-4fc60ecae052">recent our article</a> stated the react-hooks was the rotten fruit nobody should try to put on his plate. And the statement based on the real experience after one completed and another half-completed project.</p><p>But the half-completed project did not allow us etiher to get rid off react-hooks nor to proceed the same way. It was a moment we all have to sit at the table and to think a lot about the further project fate.</p><p>Actually it was not as tragic as it sounds, everybody of the team liked the hooks, everybody was sure we would continue to use them and there was a consensus that our troubles had been caused not the hook themselves but our misunderstanding and misuses caused mostly by a hurry.</p><p>So let’s stop and think.</p><p>First we need to move from emotions to facts. What was the real pain of using react hooks?</p><ol><li>Unpredictable re-rendering</li><li>Terrible huge spagetty-style shared state code including context, reducers, real problem logic.</li></ol><p>The reason of the problem 1 was discovered almost immediately. Following the pattern: “create a reducer, put it in the top-level context, pull it out of the context and use it where it would be needed”.</p><p>This pattern is terrible wrong: as soon as a [state, reducer] pair is created in the top level component we literraly say: “the top level component is intersted in the state and should be updated on this state change”. As a resul any(!) state change caused all the components to be re-rendered from top to bottom. The fact we did not use the state for the render but just store it in the context seems does not mater for the current hooks implementation.</p><p>From this point the first rule was born: “create a state only in the components that really need the state”. Don’t attempt to create a state for further use — although one could manage the re-renders with the memos, but it would cause terrible code and wasting work time.</p><p>Sounds simple. But how to share the state between the components if we can not create the state in the parent component?</p><p>And the answer to this question is simple as well: Don’t keep the state inside the react or react-hook part of you app at all. This was a real lighting strike making us to re-think all the approach to the react-hook based application.</p><p>With the previous state management frameworks, both redux and mobx it was clear we should separate logic and presentation but the relation between React and state was tight anyway.</p><p>With the hooks we told ourselves: “forget about React, completely, develop state machine and send notifications about the state changes”</p><pre>- src<br>  <strong>- app</strong><br>  - react<br>    - components<br>    - hooks<br>...</pre><p>Now we are not bound to any react-related implementations while implementing the business-logic in “app” folder and we do not care about the integration at all. The only problem is to decide how to notify outside world about the state changes. Our solution is to use RxJs but it is a question of taste.</p><p>The hooks in the react do not need share the state anymore — they just get state from the global app and being notified about the state change.</p><p>Let’s see the (almost) real life example — authorisation.</p><pre>- src<br>  - app-rx<br><strong>    - auth<br>      <em>index.ts</em><br>      <em>default.ts</em></strong></pre><p>We use “app-rx” folder name in order to emphases we use Rx as an interface to outer world.</p><p>By convention “index.ts” contains interfaces and “default.ts” an implementation used within the app (in contrast to “mock”ed implementations used in tests”).</p><p><em>index.ts</em></p><pre><strong>import </strong>{Subject} <strong>from &#39;rxjs&#39;</strong>;<br><br><strong>export interface </strong>Auth {<br>  <strong>isReady</strong>: <strong>boolean</strong>; // auth loaded the info about its state<br>  <strong>isLoggedIn</strong>: <strong>boolean</strong>; // some user logged in<br>  <strong>readonly sIsReady</strong>: Subject&lt;<strong>boolean</strong>&gt;;    // hooks will subscribe<br>  <strong>readonly sIsLoggedIn</strong>: Subject&lt;<strong>boolean</strong>&gt;; // these observables<br>// actions</pre><pre>  <strong>loginWithPassword</strong>: (email: <strong>string</strong>, password: <strong>string</strong>) =&gt; <strong>void</strong>;<br>  <strong>logout</strong>: () =&gt; <strong>void</strong>;<br>}</pre><p>There’s nothing redux/mobx/etc related here — we really like to have this freedom.</p><p><em>default.ts</em></p><pre><strong>import </strong>{Subject} <strong>from &#39;rxjs&#39;</strong>;<br><strong>import </strong>firebase <strong>from &#39;../../firebase&#39;</strong>; // thin wrapper above FB Auth<br><strong>import </strong>{Auth} <strong>from &#39;./index&#39;</strong>;</pre><pre>// we decided to have default singleton <br>// implementing Auth interface</pre><pre><strong>export const </strong>rxAuth: Auth = {<br>  <strong>isLoggedIn</strong>: <strong>false</strong>,  // initial <br>  <strong>isReady</strong>: <strong>false</strong>,     // state<br>  <strong>sIsLoggedIn</strong>: <strong>new </strong>Subject&lt;<strong>boolean</strong>&gt;(), // just create<br>  <strong>sIsReady</strong>: <strong>new </strong>Subject&lt;<strong>boolean</strong>&gt;(),    // observables<br>// actions just trigger firebase </pre><pre>  loginWithPassword: (email: <strong>string</strong>, password: <strong>string</strong>): Promise&lt;<strong>void</strong>&gt; =&gt;<br>    firebase.<em>auth</em>().signInWithEmailAndPassword(email, password),<br>  logout: (): Promise&lt;<strong>void</strong>&gt; =&gt;<br>    firebase.<em>auth</em>().signOut()<br>};</pre><pre>// *** the most interesting part ***<br>// we listen for FB Auth state changes and <br>// set the app state accordingly notifing <br>// outside world the state chneged</pre><pre>firebase.<em>auth</em>().onAuthStateChanged(user =&gt; {<br>  <strong>if </strong>(!rxAuth.<strong>isReady</strong>) {<br>    rxAuth.<strong>isReady </strong>= <strong>true</strong>;<br>// send notification auth sub-system went to defined state<br>   rxAuth.<strong>sIsReady</strong>.next(<strong>true</strong>);<br>  }<br>// send notification auth sub-system changed its login status rxAuth.<strong>sIsLoggedIn</strong>.next(<strong><em>Boolean</em></strong>(user));<br>});</pre><p>For the dependency injection we use factory pattern — not sophisticated by simple and effictive</p><pre>- src<br>  - app-rx<br>    - auth<br>      <em>index.ts</em><br>      <em>default.ts</em><br>  - <strong>di-default</strong><br>    <strong><em>index.ts</em></strong></pre><p><em>index.ts</em></p><pre><strong>import </strong>{Auth} <strong>from &#39;../app-rx/auth&#39;</strong>;</pre><pre>// just return the singleton<br><strong>export const </strong><em>getAuth </em>= (): Auth =&gt; rxAuth;</pre><p>That all about the application.</p><p>Now it’s time to go to react part. Let’s create a hook we will use in the components</p><pre>- src<br>  - app<br>  - react<br>    - components<br>    - hooks<br>      - app<br>        <strong>- auth<br>          <em>use-ready.ts</em></strong><br>        ...<br>      - components<br>      ...</pre><p>The key of the hooks is to subscribe to the observables, to pass the app state to react-hook state and finally to unsubscribe.</p><p><em>use-ready.ts</em></p><pre><strong>import </strong>{<em>useEffect</em>, <em>useState</em>} <strong>from &#39;react&#39;</strong>;<br><strong>import </strong>{<em>getAuth</em>} <strong>from &#39;../../../../di-default&#39;</strong>;</pre><pre><strong>const </strong><em>useAuthReady </em>= (): <strong>boolean </strong>=&gt; {<br>// the factoty gives us a singleton<br>  <strong>const </strong>auth = <em>getAuth</em>();<br>// create the React-hooks state<br>  <strong>const </strong>[state, setState] = <em>useState</em>&lt;<strong>boolean</strong>&gt;(auth.<strong>isReady</strong>);<br>// subscribe to Auth ready <br>// and change React-hooks state every time the<br>// Auth readiness changes<br>  <strong>const </strong>subscription = auth.<strong>sIsReady</strong>.subscribe(isReady =&gt; setState(isReady));<br>// The unsubstription is obvious<br>  <em>useEffect</em>(() =&gt; (): <strong>void </strong>=&gt; {<br>    subscription.unsubscribe();<br>  });<br>// Pay attention we do not expose <strong>setState</strong> at all<br>  <strong>return </strong>state;<br>};<br><br><strong>export default </strong><em>useAuthReady</em>;</pre><p>And finally…</p><pre>- src<br>  - app<br>  - react<br>    - components<br>    - hooks<br>      - app<br>        - auth<strong><br>          </strong><em>use-ready.ts</em><br>        ...<br>      - components<br><strong>        - Workspace<br>          <em>index.tsx</em></strong><br>        App.tsx</pre><pre>      ...</pre><p><em>Workspace/index.tsx</em></p><pre><strong>import </strong>* <strong>as </strong>React <strong>from &#39;react&#39;</strong>;<br><strong>import </strong><em>useAuthReady </em><strong>from &#39;../../hooks/app/auth/use-ready&#39;</strong>;<br><strong>import </strong><em>Loading </em><strong>from &#39;../Loading&#39;</strong>;<br><strong>import </strong><em>Loded </em><strong>from &#39;../Loded&#39;</strong>;<br><br><strong>const </strong><em>Workspace</em>: React.FunctionComponent&lt;{}&gt; = (): React.ReactElement =&gt; {<br>  <strong>const </strong>isAuthReady = <em>useAuthReady</em>();<br>  <strong>return </strong>isAuthReady ? &lt;<strong>Loaded </strong>/&gt; : &lt;<strong>Loading</strong>&gt;;<br>};<br><br><strong>export default </strong><em>Workspace</em>;</pre><p>And we got exactly we wanted: we keep the global state in the implementation best fit our needs, we create react-hook states exactly where they need to exist and now we have a very thin boiler-plate layer and avoid re-draws completely.</p><p><strong>Bonus pack</strong></p><p>To add custom hooks for every RX observable is not big deal and add some semantic beauty but it is possible to use an universal hook for (almost) any observable.</p><p><em>The sample unversal BehaviorSubject hook.</em></p><pre>- src<br>  - app<br>  - react<br>    - components<br>    - hooks<br>      - app<br>        - auth<br>          <em>use-ready.ts</em><br>        ...<br><strong><em>      - rx<br>        use-behavior.ts</em></strong></pre><pre>      ...</pre><p><em>use-behavior.ts</em></p><pre><strong>import </strong>{<em>useEffect</em>, <em>useState</em>} <strong>from &#39;react&#39;</strong>;<br><strong>import </strong>{BehaviorSubject} <strong>from &#39;rxjs&#39;</strong>;</pre><pre>// the only param to useBehavior is an observable<br>// there&#39;s no need to pass default value because<br>// it can be borrowed from the BehaviorSubject&#39;s <br>// value property</pre><pre><strong>const </strong><em>useBehavior </em>= &lt;T&gt;(behavior: BehaviorSubject&lt;T&gt;): T =&gt; {<br> <strong>const </strong>[state, setState] = <em>useState</em>&lt;T&gt;(behavior.<strong>value</strong>);<br><br>  <strong>let </strong>first = <strong>false</strong>;<br>  <strong>const </strong>subscription = behavior.subscribe((value: T): <strong>void </strong>=&gt; {<br>    <strong>if </strong>(first) {<br>      setState(value);<br>    } <strong>else </strong>{<br>      first = <strong>true</strong>;<br>    }<br>  });<br> <em>useEffect</em>(() =&gt; (): <strong>void </strong>=&gt; {<br>    subscription.unsubscribe();<br>  });<br>  <strong>return </strong>state;<br>};<br><br><strong>export default </strong><em>useBehavior</em>;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d07c1434db6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React hooks — another rotten fruit]]></title>
            <link>https://medium.com/@s4y.solutions/react-hooks-another-rotten-fruit-4fc60ecae052?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fc60ecae052</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 17:12:28 GMT</pubDate>
            <atom:updated>2019-10-16T07:32:28.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>React hooks — another rotten fruit</h3><p><em>(Go to the </em><a href="https://medium.com/@s4y.solutions/the-right-way-to-cook-react-hooks-d07c1434db6b"><em>next story</em></a><em> if you do not want reading about the bad part)</em></p><p>So, we completed 1 project and moving towards the half of another attempting to replace redux and mobx with React hooks entirely.</p><p>Short summary: don’t use react hooks. It hurts the performance by 10–30%.</p><p>Longer summary: don’t use react hooks unless you are doing self contained framework with lot of stateful components.</p><p>A note for longer summary: don’t use react hooks even if you are doing self contained framework with lot of stateful components.</p><p>Explanation.</p><p>The famous videos with Dan Abramov demonstrating sample in fact show the very primitive use cases of the isolated small components with the direct relations between them so you can pass the state via props.</p><p>As soon as you need to share global state React Hooks sucks awfully. The commonly known approach to create a reducer and put it in context causes non-explainable and non-avoidable re-rendering of everything. From top to bottom. You might spent days and weeks polluting you code with React.memo and React.useMemo — it will not help. The only result is you will get “write only” code with the logic buried among those memos and parenthesis.</p><p>Even worse — re-rendering the components will cause your reducers to be recreated and useEffects to be relaunched — with all the networks requests doubled, triples and quadrupled.</p><p>You can avoid it once again with singletones, flags, etc. Well, forget about “less boilerplate” completely. Instead of solving the client’s problem you’ll be put your life on fire solving the problems of hooks.</p><p>Well what about isolated stateful component. Does it worth to switch from classes to hooks. My opinion — “no”. The silly code this.handleSomething=this.handleSomething.bind() is not much worse than its equivalent useCallback(()=&gt;handleSomething(),[]) and shouldComponentUpdate(){...} is not worse than useMemo(Component, ()=&gt;{....}, but shouldComponentUpdate always works and useMemo, useCallback, React.memo usually does not. Needless to say React.Memo does not have `nextContext` argument.</p><p>As the result— there’s no answer for question: “what are those efforts for?”. The boilerplate does not become less, it grows. The code does not become clearer — it become polluted with “memos”. The app does not become more robust or testable — it become unpredictable. The overall performance definitely drops because of re-renders.</p><p>But stop to fall in despair. Some fruits should be eaten rotten if cooked right. <a href="https://medium.com/@s4y.solutions/the-right-way-to-cook-react-hooks-d07c1434db6b">So it is about the hooks</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fc60ecae052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger Inverted]]></title>
            <link>https://medium.com/@s4y.solutions/dagger-inverted-2b0f2b996197?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b0f2b996197</guid>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Sat, 22 Jun 2019 19:12:15 GMT</pubDate>
            <atom:updated>2019-06-22T19:12:15.161Z</atom:updated>
            <content:encoded><![CDATA[<p>As soon as you have to support Android application you have to have integration tests. As soon as you have to have integration tests you have to inject mockups and spies. As soon you have to inject mockups and spies you come to <a href="https://google.github.io/dagger/">Dagger</a>. And finally you have to read its <a href="https://google.github.io/dagger/users-guide">user guide</a> spending hours if not day understanding the terms dependencies, modules, components, graphs, injects and relations between them.</p><p>For easier understanding i’d prefer to inverse the order of the terms and start from the end of the User Gude, from the very beginning of all the problems: Android’s components (i mean application, activities, services, receivers) have no idea about dependency manager and nothing could be done automatically.</p><p>Because of this we have to inject dependencies manually in some step of the component’s life cycle.</p><pre>...<br>@Inject<br>SomeType someVar;<br>...</pre><pre>OnCreate() {<br>...<br>  someDependenciesManager.<strong>inject</strong>(this)<br>}</pre><p>And from here we see the necessity of some dependency manager to exist and this is the worst documented part of the Dagger.</p><p>In Dagger documentation they call this dependency manager “a component” and although it is pretty vague term i’ll follow the suggested terminology.</p><p>So, let’s start creating the component we will use further to inject the dependencies.</p><p>Create an empty interface annotated with @Component</p><p><em>AppComponent.kt</em></p><pre><strong>import </strong>dagger.Component<br><strong>import </strong>javax.inject.Singleton<br><br>@Singleton // let&#39;s ignore Singleton annotation so far<br>@Component<br><strong>interface </strong>AppComponent {<br>}</pre><p>This interface will be used by the dagger preprocessor to create DaggerAppComponent class implementing the component builder.</p><p>In order the generation to work the few directives should be added to module gradle and the component to be referenced somewhere.</p><p>In case of Kotlin add at the top of module gradle add a directive:</p><pre>apply <strong>plugin</strong>: <strong>&#39;kotlin-kapt&#39;</strong></pre><p>and in `dependencies` section:</p><pre>dependencies {<br>    annotationProcessor <strong>&#39;com.google.dagger:dagger-compiler:2.22&#39;<br>    </strong>kapt <strong>&#39;com.google.dagger:dagger-compiler:2.22&#39; // for kotlin only<br>...<br>    </strong>implementation <strong>&#39;com.google.dagger:dagger:2.22&#39;<br>...<br>}</strong></pre><p>I used to keep the reference to Dagger component in the Application instance and create it in the protected method. This let us to override this method in the tests and use different modules with the dependencies.</p><p><em>Manifest.xml</em></p><pre>&lt;<strong>application<br>        android:name=&quot;.TheApplication&quot;</strong></pre><p><em>TheApplication.kt</em></p><pre><strong>import </strong>android.app.Application<br><br><strong>class </strong>TheApplication: Application() {<br>    <strong>companion object </strong>{<br>        <strong>lateinit var appComponent</strong>: AppComponent<br>            <strong>private set<br>    </strong>}</pre><pre>    <strong>internal fun </strong>prepareAppComponent(): AppComponent? {<br>        <strong>return </strong>DaggerAppComponent.builder().build()<br>    }<br><br>    override <strong>fun </strong>onCreate() {<br>        <strong>super</strong>.onCreate()<br>    }<br>}</pre><p>At this point Android Studio will show DaggerAppComponent in red because this class does not exist. Hit “build“ in order to make this class to be generated by dagger prepropcessor.</p><p>Now we have a Dagger component capable to make injection into Android code and it is time to create those dependencies.</p><p>First define the interface we need to implement:</p><p><em>CalculatorInterface.kt</em></p><pre><strong>interface </strong>CalculatorInterface {<br>    <strong>fun </strong>add(v1: Int, v2: Int): Int<br>    <strong>fun </strong>sub(v1: Int, v2: Int): Int<br>}</pre><p>And make a default implementation of it</p><p><em>CalculatorDefault.kt</em></p><pre><strong>class </strong>CalculatorDefault : CalculatorInterface {<br>    <strong>override fun </strong>add(v1: Int, v2: Int): Int {<br>        <strong>return </strong>v1 + v1<br>    }<br><br>    <strong>override fun </strong>sub(v1: Int, v2: Int): Int {<br>        <strong>return </strong>v1 - v2<br>    }<br>}</pre><p>There’ s nothing related to Dagger so far, but the next step will connect the requested interface with the default implementation</p><p><em>DaggerCalculatorModule.kt</em></p><pre><strong>import </strong>dagger.Module<br><strong>import </strong>dagger.Provides<br><strong>import </strong>javax.inject.Singleton<br><br>@Module<br><strong>class </strong>DaggerCalculatorModule {<br>    @Provides<br>    @Singleton<br>    <strong>fun </strong>provideCalculator():CalculatorInterface{<br>        <strong>return </strong>CalculatorDefault()<br>    }<br>}</pre><p>The important annotation is @Module — it lets to connect DaggerCalculatorModule to the component — just change AppComponent.kt</p><pre><strong>import </strong>dagger.Component<br><strong>import </strong>solutions.s4y.dagger2demo.calculator.DaggerCalculatorModule<br><strong>import </strong>javax.inject.Singleton<br><br>@Singleton<br>@Component(modules = [DaggerCalculatorModule::<strong>class</strong>]) // &lt;---<br><strong>interface </strong>AppComponent {<br>}</pre><p>At this point we have a graph of dependencies from `AppComponent` at the top to the “branch” — Calculator module and to the final leaf — Calculator default implementation of the Calculator interface.</p><p>The last step — make this graph accessible and usable.</p><p>Store the Dagger component in the static property of the Application class</p><p><em>TheApplication.kt</em></p><pre><strong>import </strong>android.app.Application<br><br><strong>class </strong>TheApplication : Application() {<br>    <strong>companion object </strong>{<br>        <strong>lateinit var appComponent</strong>: AppComponent<br>            <strong>private set<br>    </strong>}<br><br>    <strong>protected fun </strong>prepareAppComponent(): AppComponent {<br>        <strong>return </strong>DaggerAppComponent.builder().build()<br>    }<br><br>    <strong>override fun </strong>onCreate() {<br>        <strong>super</strong>.onCreate()<br>        <strong>appComponent </strong>= prepareAppComponent() // &lt;----<br>    }<br>}</pre><p>Create an injectable property for a reference to the calculator interface in the and inject the calculator implementation in onCreate method</p><p>MainActivity.kt</p><pre><strong>class </strong>MainActivity : AppCompatActivity() {<br>    @Inject<br>    <strong>lateinit var calculator</strong>: CalculatorInterface // &lt;---<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br>        TheApplication.<strong>appComponent</strong>.inject(<strong>this</strong>) // &lt;--<br>    }<br><br>    <strong>fun </strong>onAddClick(view: View){<br>        result.setText((<strong>calculator</strong>.add( v1.<em>text</em>.toString().<em>toInt</em>(), v2.<em>text</em>.toString().<em>toInt</em>())).toString())<br><br>    }<br><br>    <strong>fun </strong>onSubClick(view: View){<br>        result.setText((<strong>calculator</strong>.sub( v1.<em>text</em>.toString().<em>toInt</em>(), v2.<em>text</em>.toString().<em>toInt</em>())).toString())<br>    }<br>}</pre><p>IDE will show `TheApplicaiton.appComponent.inject` in red once again — we still do not have this method in the DaggerAppComponent generated implementation. Let’s add it to the component interface</p><p><em>AppComponent.kt</em></p><pre><strong>import </strong>dagger.Component<br><strong>import </strong>solutions.s4y.dagger2demo.calculator.DaggerCalculatorModule<br><strong>import </strong>javax.inject.Singleton<br><br>@Singleton<br>@Component(modules = [DaggerCalculatorModule::<strong>class</strong>])<br><strong>interface </strong>AppComponent {<br>    <strong>fun </strong>inject(activity: MainActivity) // &lt;---<br>}</pre><p>…and rebuild the project. Now that’s all. The application will build the component on create itself, the main activity will ask the component to fine the implementation of calculator interface, create an instance (the singleton as the annotation said) and assign this instance to the injectable property.</p><p>There is also adagger-android library to eliminate the need of implicit calls of injection which may make the code simpler with some magic — some may love it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b0f2b996197" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A reason to do not use LiveData, ViewModel, Room]]></title>
            <link>https://medium.com/@s4y.solutions/a-reason-to-do-not-use-livedata-viewmodel-room-1c3a343fb08e?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3a343fb08e</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Sat, 22 Jun 2019 16:25:50 GMT</pubDate>
            <atom:updated>2019-06-22T16:32:35.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>A reason to do not use LiveData, ViewModel and Room</h3><p>The short story: after the digging into the rudimentary documentation, searching stackoverlow for magic gradle directives and preparing the terrible boilerplate of databases, repositories, factories we end up with:</p><pre>java.lang.NullPointerException: Attempt to invoke virtual method &#39;int solutions.s4y.dagger2demo.data.Value.getI()&#39; on a null object reference<br>        at solutions.s4y.dagger2demo.MainActivity$onCreate$2.onChanged(MainActivity.kt:18)<br>        at solutions.s4y.dagger2demo.MainActivity$onCreate$2.onChanged(MainActivity.kt:10)</pre><p>against the innocent code</p><pre><strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>    <strong>super</strong>.onCreate(savedInstanceState)<br>    setContentView(R.layout.<em>activity_main</em>)<br>    <strong>val </strong>model = <em>getValueListModel</em>(<strong>this</strong>)<br><br>    model.<strong>v1</strong>.observe(<strong>this</strong>, <em>Observer</em>&lt;Value&gt; <strong>{ </strong>v1.setText(<strong>it</strong>.<strong>i</strong>) <strong>}</strong>)<br>&gt;&gt; 18:model.<strong>v2</strong>.observe(<strong>this</strong>, <em>Observer</em>&lt;Value&gt; <strong>{ </strong>v2.setText(<strong>it</strong>.<strong>i</strong>) <strong>}</strong>)<br>}</pre><p>…and with a meaningless backtrace of 3rd party and generated code.</p><p>And it is really <a href="https://medium.com/@s4y.solutions/android-livedata-vs-rxjava-b7fd4e166f24">no sense</a> to spent another day finding out the reason of where, when and why the live object is null instead of just</p><pre>rxModel.subscribe(... v1.text = model.i )</pre><p>Moreover `Room` is seems to be just another sequel of “Weekend at Bernie’s” with attempt to make another dead-born DAO implementation to look like an alive creature and spent time and money of the employer/client for sake of the pile of code full of the magic annotations which will become obsolete in less than 2 years and will have to be completely rewritten because of Room2 or Loan3 release.</p><p>Well the ability of ViewModels to keep the state between active/fragments state changes seems to be attractive but one have to stop at some point and keep them as simple and independent as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3a343fb08e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks: shared reducer in the not so bad way]]></title>
            <link>https://medium.com/@s4y.solutions/react-hooks-shared-reducer-in-the-not-so-bad-way-7f4ab6837ea8?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f4ab6837ea8</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Fri, 03 May 2019 05:26:44 GMT</pubDate>
            <atom:updated>2019-05-04T07:00:45.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Y6nXS3H5Sh-DdmiddWdY9Q.png" /><figcaption>And upon Allah is the direction of the [right] way, and among the various paths are those deviating. And if He willed, He could have guided you all.</figcaption></figure><p>So, despite my previous <a href="https://medium.com/@s4y.solutions/react-hooks-far-not-a-silver-bullet-31196b41afd5">statement</a> i still can not stop from the attempts to get rid of 3rd party React state management frameworks and live with the React hooks only.</p><blockquote>At the moment my strong opinion is: one should keep use Redux as if hooks would have not existed and use hooks ONLY in the cases you would have used class before the hooks had appeared</blockquote><p>So, the frame of the hooks implementing shared state will be a context with a reducer kept inside it as it was advised many times in the other articles. But my article is about the unified code and file structures which seemed become standard in S4Y.</p><p>First about the files. In the simplest case there’s a file called context.ts in the most inner folder of the source code where the state is to be consumed. If the logic of the state seems to be pretty complex, the file transforms to a folder context with the index.ts inside it.</p><p>It is worth to mention we used a term context here not in the meaning of the “React context” but rather “a context of (a part of) the application”. In the other frameworks/standards they use “Models”, “Repository”, “Factory”, “Manger” for this. But for reason of the beauty we preferred to use a term “context” even it clashes with “React context”. We can afford it because react context use will be minimal in our coding style and mainly under the hood.</p><p>Well, let’s walk into internals of context.ts and implement a simple state of components of a some tree viewer. The modelled tree will have rather complicated structure of two levels: top folders of folders and one inner level of folders of features. This assumption let us to demonstrate some TypeScript use cases.</p><pre><strong>enum </strong>Level {<em>TOP</em>, <em>FEATURES</em>}</pre><pre><strong>const </strong>defaultCatalogUiState = {<br>  <strong>featureEdit</strong>: <strong>null as </strong>Feature,<br>  <strong>folderEdit</strong>: <strong>null as </strong>Folder,<br>  <strong>level</strong>: Level.<em>TOP</em>,<br>};</pre><pre><strong>type </strong>CatalogUiState = <strong>typeof </strong>defaultCatalogUiState;</pre><p>This has no direct connection to React yet. We start modelling a state to be used in the reducer. Pay attention instead of defining state interface and using it as constant type there’s a types constant and a type derived from it. This way we avoid the duplication of the almost identical curly brackets: one for an interface and another for a constant.</p><pre><strong>enum </strong>ActionType {<em>START_FOLDER_EDIT</em>, <em>COMMIT_EDIT</em>, <em>CANCEL_EDIT </em>}<br><br><strong>type </strong>Action =<br>  { <strong>folder</strong>: Folder; <strong>level</strong>: Level; <strong>type</strong>: ActionType.<em>START_FOLDER_EDIT </em>} |<br>  { <strong>type</strong>: ActionType.<em>COMMIT_EDIT </em>} |<br>  { <strong>type</strong>: ActionType.<em>CANCEL_EDIT </em>}<br>  ;</pre><p>Once again, there’s nothing about React yet. You can use the very same pattern for Redux state and action implemented with TypeScript. One can afford such verbose definition because of Hooks Reducer tends to be small and this is where Hooks Reducers won Redux reducers.</p><pre><strong>const </strong><em>reducer </em>= (state: CatalogUiState, action: Action): CatalogUiState =&gt; {<br>  <strong>switch </strong>(action.<strong>type</strong>) {<br>    <strong>case </strong>ActionType.<em>START_FOLDER_EDIT</em>:<br>      <strong>return </strong>{...state, <strong>folderEdit</strong>: action.<strong>folder</strong>, <strong>level</strong>: action.<strong>level</strong>};<br>    <strong>case </strong>ActionType.<em>COMMIT_EDIT</em>:<br>    <strong>case </strong>ActionType.<em>CANCEL_EDIT</em>:<br>      <strong>return </strong>{...state, <strong>featureEdit</strong>: <strong>null</strong>, <strong>folderEdit</strong>: <strong>null</strong>};<br>    <strong>default</strong>:<br>      <strong>return </strong>state;<br>  }<br>};</pre><p>The reducer itself. There’s nothing that could say it is not well known Redux reducer and it is very-very good: learning curve of Hooks reducers is almost flat.</p><pre><strong>interface </strong>CatalogUi {<br>  <strong>cancelEdit</strong>: () =&gt; <strong>void</strong>;<br>  <strong>commitEdit</strong>: () =&gt; <strong>void</strong>;<br>  <strong>isFolderEdited</strong>: (folder: Folder) =&gt; <strong>boolean</strong>;<br>  <strong>startEditFolder</strong>: (folder: Folder, level: Level) =&gt; <strong>void</strong>;<br>}</pre><p>And this is where the S4Y way starts: i hate to expose action types, internal state and dispatches outside of state manager implementation. With the Redux we achieve the same via connect and selectors, but React hooks give us a nice interface to manage the state.</p><p>Pay attention in the code above i completely hid the state structure — an end user will have to use the getterisFolderEdited to access the internal state. If you do not like this approach (and i understand why) use the different code</p><pre><strong>interface </strong>CatalogUi extends CatalogUiState {<br>  <strong>cancelEdit</strong>: () =&gt; <strong>void</strong>;<br>  <strong>commitEdit</strong>: () =&gt; <strong>void</strong>;<br>  <strong>startEditFolder</strong>: (folder: Folder, level: Level) =&gt; <strong>void</strong>;<br>}</pre><p>Now you’ll be able to access the state fields directly and the interface has to contain only modifiers and, probably, some (memoized) accessors.</p><p>Ok. At this point we have almost everything to create React context instance.</p><pre><strong>export const </strong>contextCatalogUi = React.<em>createContext</em>&lt;CatalogUi | <strong>null</strong>&gt;(<strong>null</strong>);</pre><p>This the first place the things become no so clear. Why there’s a null and where is the implementation of the CatalogUi interface. Why it is not possible to create an instance of the CatalogUi and pass it to .createContext?</p><p>The short answer: “hooks must be used only within functional component” and want to call “useReducer” to create the React hooks reducer and put it into the context. So let’s skip a bit of our state manager and go to the use case of it.</p><p>This is how we are going to add the created context to the components tree:</p><pre><strong>const Workspace</strong>: React.FunctionComponent&lt;{}&gt; = (): React.ReactElement =&gt; &lt;<strong>div className=&quot;workspace&quot;</strong>&gt;<br>  &lt;<strong>contextCatalogUi.Provider value=</strong>{<em>initialCatalogUi</em>()}&gt;<br>    &lt;Folders/&gt;<br>  &lt;/<strong>contextCatalogUi.Provider</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><pre>export <strong>Workspace</strong>;</pre><p>Remember the constant contextCatalogUi initialised with the call of React.createContext a step above. It was created without use of any hooks and this why it was possible to create it outside the functional component. Moreover it is singleton because of how import works.</p><p>Calling its method .provider we create a real context to be propagated down to the inner components and to bear a some value. Needless to say the value will be the instance of the CatalogUi implementation which will let the inner component to share the single state through the context value methods.</p><pre><strong>const FolderPreferences</strong>: React.FunctionComponent&lt;{}&gt; = (): React.ReactElement =&gt; {<br>  const <strong>catalogUi</strong> = React.useContext(<strong>contextCatalogUi)</strong>;<br>  return {<strong>catalogUI.isFolderEdited</strong> &amp;&amp; ...}<br>}</pre><pre>export <strong>FolderPreferences</strong>;</pre><p>The interesting part is how we get the instance of CatalogUi implementation during the creation of the context provider: calling a function initCatalogUi let us to use any use* React Hooks API because it was called from within the functional component Workspace.</p><pre><strong>export const </strong><em>initialCatalogUi </em>= (): CatalogUi =&gt; {<br>  <strong>const </strong>[<br>    catalogUiState,<br>    dispatch,<br>  ] = React.<em>useReducer</em>&lt;React.Reducer&lt;CatalogUiState, Action&gt;&gt;(<em>reducer</em>, defaultCatalogUiState);<br>  <strong>return </strong>{<br>    cancelEdit: (): <strong>void </strong>=&gt; dispatch({<strong>type</strong>: ActionType.<em>CANCEL_EDIT</em>}),<br>    commitEdit: (): <strong>void </strong>=&gt; dispatch({<strong>type</strong>: ActionType.<em>COMMIT_EDIT</em>}),<br>    isFolderEdited: (folder): <strong>boolean </strong>=&gt; catalogUiState.<strong>folderEdit</strong>.<strong>id </strong>=== folder.<strong>id</strong>,<br>    startEditFolder: (folder, level): <strong>void </strong>=&gt; dispatch({folder, level, <strong>type</strong>: ActionType.<em>START_FOLDER_EDIT</em>}),<br>  };<br>};</pre><p>There’s nothing new or special in the code: we call React.useReducer and wraps the calls of the dispatch to the method properties of the object implementing CatalogUi interface. Repeat once again: we CAN call useReducer because initialCatalogUi is called from within the functional component Workspace.</p><p>And now the summary from the bottom to top:</p><p>with this pattern we imports exactly 2 values from the state manager: a constant with the React context and a function to create an instance of (the implementation of) the interface. That’s all. Context’s constant is used to create a provider and a function to create a value to be passed to that provider.</p><p>The consuming of this provider is as simple as calling of useContext and utilising the returned interface.</p><h4>The note 1.</h4><p>The pattern of</p><pre>&lt;context.Provider value={initInterface()}&gt; ... &lt;/context.Provider&gt;</pre><p>may seem rather cumbersome and can be simplified with something like this</p><pre>export const <strong>ContextProvider</strong> = ({children})=&gt;<br>  &lt;<strong>context.Provider</strong> value={initInterface()}&gt;{children}&lt;/<strong>context.Provider</strong>&gt;</pre><p>In this case this functional component would be the only export of the state manager and the use of it would be as easy as</p><pre><strong>const Workspace</strong>: React.FunctionComponent&lt;{}&gt; = (): React.ReactElement =&gt; &lt;<strong>div className=&quot;workspace&quot;</strong>&gt;<br>  &lt;<strong>ContextProvider&gt;</strong><br>    &lt;Folders/&gt;<br>  &lt;/<strong>ContextProvider</strong>&gt;<br>&lt;/<strong>div</strong>&gt;</pre><pre>export <strong>Workspace</strong>;</pre><p>The only reason we do not go this way is not willing to change .ts extenstion of the file with context and reducer code to .tsx. The creating a separated .tsx file just for one line component seemed to be overkill. Since you used to write down &lt;context.Provider value={initial*}&gt; there’s now need for further simplification indeed.</p><h4>The note 2.</h4><p>The naming the function to create to implementation of the state interface as initial* does not seem to be the perfect and we thought about something like getSingleton* but decided it may be the cases there will be few the instance of the context and stay with the initial* naming conventions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4ab6837ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React hooks — far not a silver bullet]]></title>
            <link>https://medium.com/@s4y.solutions/react-hooks-far-not-a-silver-bullet-31196b41afd5?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31196b41afd5</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Sat, 13 Apr 2019 08:46:16 GMT</pubDate>
            <atom:updated>2019-05-03T05:20:09.766Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>React hooks — far not a silver bullet</h3><p>Should we give up redux for sake of react hooks. The short answer is simple: no.</p><p>The longer answer is — “hooks’ realm is exactly where a redux developer has to type class word“.</p><p>And the reason to do not give up with redux is the fact: “react hooks can’t share state between components”.</p><p>Let’s see the common task: click a button and change the state of its sibling. It can not be solved with vanilla hooks. Every component has its own state and the button state change will not affect the sibling state.</p><p>One could say “use context, they provided hook for it”. Well, starting from this place i already doubt that the authoring the context, adding providers (by the way, are you sure you really understand the difference of a value passed to .createContext and a value passed to value= of contextProvider ?), adding subscribers is still easy and more readable then reduxconnect is.</p><p>But a context is not just complex, weird and verbose. The worse thing is re-rendering of the subscribers it causes. Add extra work hours to detect and fix those re-renders of “StatusA” component because of the context changes caused by update of “StatusB” component. Extra work hours to pollute your code with memo and useCallback and to solve the problem that did not exist before the hooks.</p><p>As a summary… Hm. I like hooks. But just because i hate class . If i had not most probably i would have called react hooks “another useless invention of the industry”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31196b41afd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A reason to do not use FlowJS ever]]></title>
            <link>https://medium.com/@s4y.solutions/a-reason-to-do-not-use-flowjs-ever-a16e9768aab8?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a16e9768aab8</guid>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 17:33:46 GMT</pubDate>
            <atom:updated>2019-04-02T00:21:17.647Z</atom:updated>
            <content:encoded><![CDATA[<p>If your JS project already used or is going to use some module path mapping, say with webpack, run away from FlowJS as fast as you can. In the other case even Stackoverflow will not save you from the wasting day or two without any result.</p><p>The things are worse than “just not work”. It sometimes work, sometimes throws error and sometimes just fails saying “No errors”.</p><p>The logs contains mumbo-jumbo messages. If you are able to find them.</p><p>And after adding the magic spelling to .flowconfig :</p><pre>[options]<br>module.system.node.resolve_dirname=node_modules<br>module.system.node.resolve_dirname=src</pre><p>you are not supposed to start working though. It sometimes will lint, sometimes not.</p><p>This is correct code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*fUSgSinbr5Eol9WuVgG1lg.png" /></figure><p>This is obviously incorrect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*FrxHWy8BwwT5xGPsri1TYQ.png" /></figure><p>Flowjs does not care.</p><p>You may even set the path to something non existing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*5RqSfYdXMVyWOGDKzp10Jw.png" /></figure><p>and fallback to CLI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*vwLOUwUK8d0AF2cwdfW5Xw.png" /></figure><p>FlowJS will still phew on you. No word about wrong (or right) path. Just report “everything is ok” . And there’s a reason for <a href="https://github.com/facebook/flow/pull/5850">that</a>. They knew they would break the only solution they had suggested and provided nothing but vague murmuring buried in github comments about “mapping” options they wrote some unhappy Friday night.</p><p>Besides “mapping” will still not work because it maps relative paths to `node_modules` and lose them there, it will do it *silently*. You will never know the module path is wrong. Or sometimes know, sometimes don’t.</p><p>And finally, after you have given up with nice relative paths and rollback to ../../something and empty default config you get</p><pre>Cannot resolve module `reselect`.<br>   4| import { createSelector } from &#39;reselect&#39;;</pre><p>…and even</p><pre>Spawned flow server (pid=4617)<br>Logs will go to /private/tmp/flow/zSVolumeszSHDzSUserszSdsazSMyProjectszSmap2online.log<br>Monitor logs will go to /private/tmp/flow/zSVolumeszSHDzSUserszSdsazSMyProjectszSmap2online.monitor_log<br>Error: Failed to start server. There is already a server running.</pre><p>The way it work (actually does not work) with the modules could cause heart-attack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*HSH8X__AgudViXJgQCCu4g.png" /><figcaption>Why???!!!</figcaption></figure><p>…despite even</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*sdQyJ4o8dNUDMFoL3NtF7g.png" /><figcaption>let’s try to copy flow type def from node_module to lebdef — it does not help either</figcaption></figure><p>Oh, jeezz. So moronic. But still not the end. <a href="https://github.com/facebook/flow/issues/2221">FlowJS does not work with Object.values</a>. No way. And they do not want it would work ever.</p><p>Do you want more?</p><p>This seems to be ok:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*l2KUi5Pbiz33Ncc3JGlCCw.png" /></figure><p>but if you inline the Object.keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*VnTMASyQolRWbbOZi5QSuA.png" /></figure><p>… with another same mumbo-jumbo “explanation”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*89ijHetCCT4KoRl_E_n4mQ.png" /></figure><p>TypeScript rules. No doubt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a16e9768aab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android LiveData vs RxJava]]></title>
            <link>https://medium.com/@s4y.solutions/android-livedata-vs-rxjava-b7fd4e166f24?source=rss-486b6274650a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7fd4e166f24</guid>
            <category><![CDATA[rxjava2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Sergey Dolin]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 07:47:54 GMT</pubDate>
            <atom:updated>2019-11-04T18:42:57.080Z</atom:updated>
            <content:encoded><![CDATA[<p>We just’ve lunched Android project in which tried to adopt the Android Jet pack’s feature called <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> and replace RxJava snippets with it.</p><p>Short story is “we’ve rollbacked all the changes and wiped out LiveData completely” and summary is “you do not need LiveData if already used to use RxJava but it worth to take look at LiveData if want to avoid RxJava learning curve”</p><p>First disadvantage of LiveData they are all about UI. It is cumbersome to use them to get updates from a service to service.</p><p>Next they do not give you freedom of to choose threads (do you need it?) — you only have “ui thread” and “current thread” and only one direction of switch “from current to ui”. Generally it is enough, but still brings some uneasiness. The worst thing is the sender of the change notification has to make switch. If a background service sends notification to live data object it must use postValue method to ensure the value change will be observed on the main UI thread. But who said the receiver will be ui? The RxJava’s approach to choose a thread during the subscription, not in time of the sending is much more appropriate.</p><p>Actually the only advantage of LiveData over RxJava we have noticed is they automatically subscribe and unsubscribe on Activity life cycle events (or over android components implementing life cycle). So loosing all the power of RxJava for sake of getting rid off, well, dozen lines like compositeDisposable.add(...) in onResume and oneCompositeDisposable.dispose in onPause looks like obvious overprice.</p><p>But from other hand. If one comes to me having not knowledge of RxJava i would definitely say: “Use LiveData instead — they will cover 90% of the real android developer needs, and you will be able to use them after few hours of reading”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7fd4e166f24" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>