<?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 Habib Ridho on Medium]]></title>
        <description><![CDATA[Stories by Habib Ridho on Medium]]></description>
        <link>https://medium.com/@habibridho?source=rss-9010b5273d08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0z8aZW7fOOiUoaazMSnzVg.jpeg</url>
            <title>Stories by Habib Ridho on Medium</title>
            <link>https://medium.com/@habibridho?source=rss-9010b5273d08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:59:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@habibridho/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[How to Easily Setup Wordpress Using Docker Compose]]></title>
            <link>https://medium.com/@habibridho/how-to-easily-setup-wordpress-using-docker-compose-102166c40cfa?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/102166c40cfa</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 01:34:39 GMT</pubDate>
            <atom:updated>2020-03-30T01:34:39.454Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we learned how to setup Wordpress using Docker. We ran two containers: wordpress and mysql, and connect them using docker network. We ran them imperatively by running multiple commands to get it done.</p><p>However, we may want to have a script to do it so that we don’t need to run the commands every time we want to start wordpress. Luckily, Docker has a tool for our case: Docker Compose. We can write a yaml file that consists our requirements and start them with a single command.</p><h3>Prerequisite</h3><p>First, we need docker-compose installed on our machine by simply running docker-compose -v. If it is not installed on our machine yet, we need to install it first by following <a href="https://docs.docker.com/compose/install/">this instructions</a>.</p><h3>Create Compose File</h3><p>Next, we need to create a new docker-compose.yml file and fill it with wordpress and mysql setup. The filename actually can be anything, but if we use other name we need to specify the file when running the compose command.</p><pre>version: &quot;3&quot;<br>services:<br>  wordpress:<br>    container_name: my_wordpress<br>    image: wordpress<br>    ports:<br>      - &quot;8080:80&quot;<br>    links:<br>      - mysql<br>    environment:<br>      WORDPRESS_DB_HOST: mysql<br>      WORDPRESS_DB_USER: root<br>      WORDPRESS_DB_PASSWORD: &quot;12345&quot;<br>      WORDPRESS_DB_NAME: wordpress<br>  mysql:<br>    container_name: my_mysql<br>    image: &quot;mysql:5.7&quot;<br>    volumes:<br>      - ./.mysql:/var/lib/mysql<br>    environment:<br>      MYSQL_DATABASE: wordpress<br>      MYSQL_ROOT_PASSWORD: &quot;12345&quot;</pre><p>There is a lot going on that file, let’s dissect it one by one. The first field is version which tells Compose what file format that we use. Certain field may not be recognized by a certain Compose version, so check which version is supported by the Compose installed on your machine <a href="https://docs.docker.com/compose/compose-file/#compose-and-docker-compatibility-matrix">here</a>.</p><p>Our second field is services which describe what services we want to run. In this case, we will run wordpress and mysql container. In each service, we have an optional container_name field that will be used as the container name. If we don’t specify container name, Compose will generate it automatically.</p><p>Next, we have image field which tells Compose which docker image we want to use. Since we want wordpress to be accessible outside of the container, we open port-mapping from 8080 on our host to 80 port of the container by defining it in ports field.</p><p>We learned in the previous article that we need to connect wordpress and mysql container so that they can communicate with each other. In this case, we use links to do that by simply specify which other container we want to connect this service to.</p><p>We use environment field to list down all the environment variables that need to be set in each containers. Lastly, in mysql service, we mount a volume to it in the volume field. We link .mysql folder on the host to /var/lib/mysql on mysql container so that database data can be persisted even if we shutdown the container. If we don’t have .mysql folder on the host yet, Docker will create it for us.</p><h3>Run</h3><p>To run the services, we only need to run a single command. Note that -d flag will make the services run in the background.</p><pre>$ docker-compose up -d</pre><p>A little note, we need to specify the compose file name if we use non-standard name, for example some-compose.yml.</p><pre>$ docker-compose up -f some-compose.yml -d</pre><p>Although, we run the containers declaratively, we can still use docker commands to do operation on these containers. For example, if we want to go inside the database, we can use the same command as before.</p><pre>$ docker exec -it my_mysql mysql -u root -p</pre><p>To shutdown these containers, we don’t need to delete them one by one. We can simply run:</p><pre>$ docker-compose down</pre><p>In this tutorial, we make a <a href="https://medium.com/@habibridho/how-to-easily-setup-wordpress-using-docker-a798081dc577">simple wordpress setup</a> even simpler by defining the services in a yaml file. In this way, we can turn the setup on and off with a single command. Another advantage of this is that the compose file can be moved to another machine and we will have the same setup running on it. This can ease development in teams as well as deployment to testing or production machine.</p><p><a href="https://medium.com/@habibridho/docker-as-deployment-tools-5a6de294a5ff"><em>Checkout this tutorial to deploy app using Docker.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102166c40cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Easily Setup Wordpress Using Docker]]></title>
            <link>https://medium.com/@habibridho/how-to-easily-setup-wordpress-using-docker-a798081dc577?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/a798081dc577</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 13:42:55 GMT</pubDate>
            <atom:updated>2020-03-30T01:38:21.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Wordpress is an open-source content management system (CMS) that has been around for almost 2 decades. It enables people to setup blogs even online stores easily. However, for those developing Wordpress themes, plugins, or those who needs to setup Wordpress from scratch, it may involves a tedious process which includes installing php, mysql database, etc. In this tutorial, we will utilize Docker to ease that process and have Wordpress up and running in minutes.</p><h3>Prerequisite</h3><p>First of all, we need to have <a href="https://www.docker.com/">Docker</a> on our machine. We can download the installer from <a href="https://docs.docker.com/install/">this page</a> that is available for desktop and server. After it is installed, check if the cli has been installed properly by running this on the terminal.</p><pre>$ docker version</pre><pre>// Output:<br>Client: Docker Engine - Community<br> Version:           19.03.8<br> API version:       1.40<br> Go version:        go1.12.17<br> Git commit:        afacb8b<br>...</pre><h3>Setup Mysql</h3><p>Now that we have docker installed, we can install mysql database using the <a href="https://hub.docker.com/_/mysql">official mysql docker image</a>.</p><pre>$ docker run --name local-mysql -e MYSQL_ROOT_PASSWORD=12345 -d mysql:5.7</pre><p>Let’s chop down this command so that we know what is going on here. The first segment is docker run which exactly does what it says it does: running a docker container. Next, --name local-mysql sets the container name that we are creating. You can change the name with whatever you want. -e sets environment variable for running the container and here we set MYSQL_ROOT_PASSWORD which is mandatory to run this image. -d tells docker to run the container in background. Lastly, mysql:5.7 designate that we want to run version 5.7 of mysql image. We can also use mysql that will give us the latest version of the image.</p><p>Run docker container ls to check if the container is successfully created and running. If it does, let’s add a new database for our Wordpress by executing mysql in the container.</p><pre>$ docker exec -it local-mysql mysql -u root -p</pre><p>The above command is straightforward, ie. execute mysql -u root -p inside the local-mysql container. The -it flag tells docker to be interactive in executing the command and allocate pseudo-tty. After that, we will be inside mysql prompt and we can run mysql to create a new database.</p><pre>mysql&gt; create database wordpress;</pre><h3>Setup Wordpress</h3><p>Just like setting up mysql, we can use <a href="https://hub.docker.com/_/wordpress/">official wordpress image</a> to have wordpress up and running.</p><pre>$ docker run --name local-wordpress -p 8080:80 -d wordpress</pre><p>It is pretty much the same with when we run mysql, the difference is here we have -p 8080:80 which tells docker to have port mapping. Our machine’s 8080 port will be forwarded to the container’s 80 port. Now, we can access our wordpress by accessing <a href="http://localhost:8080/">http://localhost:8080</a> on the browser and complete the setup wizard there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-U9scTA8dCKm70bte2-RQ.png" /><figcaption>setup wordpress database step</figcaption></figure><p>Now, we will encounter an “error establishing a database connection” if we use localhost as our Database Host. That is because our mysql database is inside a separate docker container that is not accessible from the wordpress container.</p><p>To fix it, we need to create a new docker network and attach it to both of our containers.</p><pre>$ docker network create --attachable wordpress-network</pre><p>The above command tells docker to create a new network named wordpress-network that can be manually attached to containers. After the network is created, we can connect it to the containers.</p><pre>$ docker network connect wordpress-network local-mysql<br>$ docker network connect wordpress-network local-wordpress</pre><p>Now, let’s go back to the wordpress wizard in our browser and set local-mysql as the Database Host. We should be able to continue the wizard and have Wordpress up and running.</p><p>This tutorial shows that docker can help us simplify a wordpress setup. We don’t need to install a standalone php or mysql database which may conflict with other projects or applications. However, since docker containers are isolated from each other, there will be additional networking setup so that they can communicate. We can also use docker-compose to have a simpler and declarative setup which is <a href="https://medium.com/@habibridho/how-to-easily-setup-wordpress-using-docker-compose-102166c40cfa">covered in this article</a>.</p><p><a href="https://medium.com/@habibridho/docker-as-deployment-tools-5a6de294a5ff"><em>Checkout this tutorial to deploy app using Docker.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a798081dc577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Here is Why No One Write Generic Slice Filter in Go]]></title>
            <link>https://medium.com/@habibridho/here-is-why-no-one-write-generic-slice-filter-in-go-8b3d1063674e?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b3d1063674e</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 11:52:18 GMT</pubDate>
            <atom:updated>2019-12-13T11:52:18.271Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR it’s slow.</h4><p>Filter is a common function that is used to modify an array or a collection of data. As the name suggest, it helps us remove unwanted data from our collection. It usually comes out of the box with the programming language. Some examples:</p><pre>// Javascript<br>const arr = [1,2,3,4,5]<br>const result = arr.filter(function(val) {<br>  return val != 5<br>})<br>console.log(result)<br>// [1,2,3,4]</pre><pre>// Kotlin<br>val arr = listOf(1,2,3,4,5)<br>val result = arr.filter{ it != 5 }<br>print(result)<br>// [1, 2, 3, 4]</pre><pre># Python<br>arr = [1,2,3,4,5]<br>result = list(filter(lambda x: x not in [5], arr))<br>print(result)<br># [1,2,3,4]</pre><p>The same example would work if we use other data types such as string, float, or even custom object. Let’s see how we do it on Go.</p><pre>// Go<br>arr := []int{1, 2, 3, 4, 5}<br>result := []int{}<br>for i := range arr {<br>  if arr[i] != 5 {<br>     result = append(result, arr[i])<br>  }<br>}<br>fmt.Println(result)<br>// [1 2 3 4]</pre><p>Go doesn’t have built-in filter function to work with slice, so we need to iterate through the slice, test whether the current value match with the filter, and append the desired value to a new slice. We can extract this logic to a standalone function, so that we can reuse everywhere in the codebase.</p><pre>func Filter(arr []int, cond func(int) bool) []int {<br>  result := []int{}<br>  for i := range arr {<br>    if cond(arr[i]) {<br>       result = append(result, arr[i])<br>    }<br>  }<br>  return result<br>}</pre><pre>// usage<br>arr := []int{1, 2, 3, 4, 5}<br>  result := Filter(arr, func(val int) bool {<br>    return val != 5<br>  })<br>fmt.Println(result)<br>// [1 2 3 4]</pre><p>Now, if we have a slice of string, we need to create another function to do the similar thing.</p><pre>func Filter(arr []string, cond func(string) bool) []string {<br>   result := []string{}<br>   for i := range arr {<br>     if cond(arr[i]) {<br>       result = append(result, arr[i])<br>     }<br>   }<br>   return result<br>}</pre><pre>// usage<br>arr := []string{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;}<br>result := Filter(arr, func(val string) bool {<br> return val != &quot;c&quot;<br>})<br>fmt.Println(result)<br>// [a b d e]</pre><p>We will need to create this kind of function one-by-one for each type of slice that we need. So I wonder if we can make it generic. In fact, in the previous example in Kotlin, the built-in filter function is a generic function that can be used with any data type.</p><pre>// src: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html">https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html</a><br>inline fun &lt;T&gt; Array&lt;out T&gt;.filter(<br>    <strong>predicate</strong>: (T) -&gt; Boolean<br>): <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html">List</a>&lt;T&gt;</pre><p>Go doesn’t have Generic, so the closest thing we can achieve a generic filter function is by combining the use of empty interface (interface{}) and reflect package which implements run-time reflection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa554ee247d00b729feb4fb13f1b4524/href">https://medium.com/media/fa554ee247d00b729feb4fb13f1b4524/href</a></iframe><p>Let’s dissect this new function. First, the function receive an empty interface named arr. The type of arr can be anything, so we utilise reflect functions to get its type and the underlying value. Next, we create newContent which we will use to store the filtered result. To iterate through each slice value, we can’t use range as we do earlier because in this case Go doesn’t know that arr can be iterated. We define it as empty interface which can be anything. The reflect.Value which is the type of contentValue has a Len function that can tell us how many item it is have. This function will panic if the underlying value is not one Array, Chan, Map, Slice, or String type, so it is actually better for us to check the type first.</p><p>Inside our iteration, it is basically the same as our previous implementation: get current value and pass it cond function and if it passes the check, we append it to our resulting slice. Now, we can use this filter to both filter slice of string and int.</p><pre>// Filter Int<br>arr := []int{1, 2, 3, 4, 5}<br>result := filter.Filter(arr, <em>func</em>(val <em>interface</em>{}) bool {<br>   <em>return </em>val != 5<br>})<br>fmt.Println(result)<br>// [1 2 3 4]</pre><pre>// Filter String<br>arr := []string{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;}<br>result := filter.Filter(arr, <em>func</em>(val <em>interface</em>{}) bool {<br>   <em>return </em>val != &quot;c&quot;<br>})<br>fmt.Println(result)<br>// [a b d e]</pre><p>Now that we have the generic function, let’s compare how it perform against the specific one. We added back our first filter implementation and name it as FilterString. The following is the benchmark test that we are going to run.</p><pre><em>func </em>BenchmarkFilter(b *testing.B) {<br>   <em>for </em>i := 0; i &lt; b.N; i++ {<br>      arr := []string{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;}<br>      Filter(arr, <em>func</em>(val <em>interface</em>{}) bool {<br>         <em>return </em>val != &quot;c&quot;<br>      })<br>   }<br>}<br><br><em>func </em>BenchmarkFilterString(b *testing.B) {<br>   <em>for </em>i := 0; i &lt; b.N; i++ {<br>      arr := []string{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;}<br>      FilterString(arr, <em>func</em>(val string) bool {<br>         <em>return </em>val != &quot;c&quot;<br>      })<br>   }<br>}</pre><pre>// Result:<br>BenchmarkFilter-12                         1000000       1263 ns/op<br>BenchmarkFilterString-12                  10000000        160 ns/op</pre><p>The generic filter is almost 8 times slower than the specific one. Now let’s see how they perform when we give them 100kb of string.</p><pre>BenchmarkFilterWith100kbText-12                 50   20072488 ns/op<br>BenchmarkFilterStringWith100kbText-12          200    9463007 ns/op</pre><p>The difference is less dramatic with FilterString can only outdo the generic by about 2 times. Still, the generic implementation is slower.</p><p>The complete code used in this article can be found <a href="https://github.com/habibridho/go-filter-benchmark">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b3d1063674e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: Nil vs Empty Slice]]></title>
            <link>https://medium.com/@habibridho/golang-nil-vs-empty-slice-87fd51c0a4d?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/87fd51c0a4d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Wed, 08 May 2019 02:09:31 GMT</pubDate>
            <atom:updated>2019-09-25T03:40:45.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Slice is one of the most common data type used in Golang. It enables us to contain contiguous data of any defined type which we can append to or iterate through.</p><pre>var foo []string<br>foo = append(foo, &quot;a&quot;)<br>foo = append(foo, &quot;b&quot;)<br>foo = append(foo, &quot;c&quot;)<br>for i, v := range {<br>  fmt.Println(i, v)<br>}</pre><pre>// Output<br>0 a<br>1 b<br>2 c</pre><p>It also worth noting that an initialized Slice has an underlying hidden Array which means it shares storage with the Array. Besides length, Slice also have capacity which is the length of the underlying Array. Appending new value beyond the capacity will allocates new Array that fits the Slice elements.</p><h3>Zero Value</h3><p>In Golang, when a variable is declared without an initialization value, its value will be set to the type’s zero value. The zero value of a Slice is nil, so in our example above, when we declare var foo []string the value of foo is actually nil not an empty slice of string []. Empty slice can be generated by using Short Variable Declarations eg. foo := []string{} or make function.</p><h3>Why is This Important?</h3><pre>var nilSlice []string<br>emptySlice := make([]string, 5)</pre><pre>fmt.Println(nilSlice) // Output: []<br>fmt.Println(len(nilSlice), cap(nilSlice)) // Output: 0 0<br>fmt.Println(nilSlice == nil) // Output: true</pre><pre>fmt.Println(emptySlice) // Output: []<br>fmt.Println(len(emptySlice), cap(emptySlice)) // Output: 0 0<br>fmt.Println(emptySlice == nil) // Output: false</pre><p>The above example demonstrate how Nil Slice can fool our eye. The result of fmt.Println -ing a Nil Slice is [] just like what we’ll have for an Empty Slice. It also has the same length and capacity as Empty Slice.</p><p>Most of the time, we don’t need to treat these two differently. We can still append and iterate a Nil Slice even though its initial value is nil. However, there are other cases that might be problematic.</p><pre>type Res struct {<br>  Data []string<br>}</pre><pre>var nilSlice []string<br>emptySlice := make([]string, 5)</pre><pre>res, _ := json.Marshal(Res{Data: nilSlice})<br>res2, _ := json.Marshal(Res{Data: emptySlice})</pre><pre>fmt.Println(string(res)) // Output: {&quot;Data&quot;:null}<br>fmt.Println(string(res2)) // Output: {&quot;Data&quot;:[]}</pre><p>Golang’s encoding/json encodes Nil Slice to null which can be unacceptable if our API contract defines Data as a not null, array of string.</p><pre>var nilSlice []string<br>emptySlice := make([]string, 5)</pre><pre>fmt.Println(reflect.DeepEqual(nilSlice, emptySlice)) // Output: false<br>fmt.Printf(&quot;Got: %+v, Want: %+v\n&quot;, nilSlice, emptySlice) //Output: Got: [], Want: []</pre><p>Another problem is when we compare these two using reflect.DeepEqual which commonly used under the hood in assertion library. The comparison will be false which makes the assertion to fail, but the assertion message gives us the same [] which gives us no sleep.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87fd51c0a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Navigation Architecture Component Tutorial]]></title>
            <link>https://medium.com/@habibridho/android-navigation-architecture-component-tutorial-c34f220232df?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/c34f220232df</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[android-tutorials]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Tue, 30 Oct 2018 16:10:38 GMT</pubDate>
            <atom:updated>2018-10-30T16:10:38.262Z</atom:updated>
            <content:encoded><![CDATA[<p>Android Studio 3.2 is finally on the stable channel and that means we can try Android <a href="https://developer.android.com/jetpack/">Jetpack</a> without too much headache. The first thing I want to try is the Navigation Architecture Component (NAC). Version 3.2 provides a Navigation Editor which resembles Xcode’s Storyboard, so now we can communicate the application flow to non-technical team in a more intuitive way.</p><h3>Install Dependencies</h3><p>First thing first, we should install all the dependencies required to utilise the NAC. As of Android Studio 3.2.1, these dependencies are not included by default when we create a new project.</p><pre>// app level build.gradle<br>apply plugin: &#39;com.android.application&#39;<br>apply plugin: &#39;androidx.navigation.safeargs&#39;<br>...</pre><pre>android {<br>...<br>}</pre><pre>dependencies {<br>...<br>  implementation &quot;android.arch.navigation:navigation-fragment-ktx:$nav_version&quot;<br>  implementation &quot;android.arch.navigation:navigation-ui-ktx:$nav_version&quot;<br>}</pre><pre>// project level build.gradle<br>buildscript {<br>...<br>  ext.nav_version = &#39;1.0.0-alpha06&#39;<br>  dependencies {<br>    ...<br>    classpath &quot;android.arch.navigation:navigation-safe-args-gradle-plugin:$nav_version&quot;<br>  }<br>...<br>}</pre><h3>Create Navigation Resources</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHmoDnBoVdAl3fKxAalShQ.png" /></figure><p>To create a new navigation resources, we can go to File -&gt; New -&gt; Android Resource File. Pick a name and choose “Navigation” in Resource Type and click “OK”. This will create a navigation resource directory if we are yet to have it, and create a nav_graph.xml file. Let’s open the nav_graph.xm file and we will have a nice Navigation Editor in the design tab. We can see on the right side of the editor, there is a Destinations pane which have two sections: Host and Graph. The Graphs are the view that we are able to navigate into. Each Graph will be swapped in and out to the Host when the navigation happen.</p><h3>Create Navigation Host</h3><p>In this example, we will use our MainActivity as our Navigation Host. To do this we will need to insert a navigation fragment inside our activity_main.xml and override onSupportNavigateUp method to handle the back navigation.</p><pre>// activity_main.xml<br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;fragment<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:id=&quot;@+id/nav_host_fragment&quot;<br>        android:name=&quot;androidx.navigation.fragment.NavHostFragment&quot;<br>        app:navGraph=&quot;@navigation/nav_graph&quot;<br>        app:defaultNavHost=&quot;true&quot;/&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><pre>// MainActivity.kt<br>...<br>class MainActivity : AppCompatActivity() {<br>  ...<br>  override fun onSupportNavigateUp(): Boolean = <em>findNavController</em>(R.id.<em>nav_host_fragment</em>).navigateUp()<br>}</pre><h3>Create Navigation Graph</h3><p>In this example we will create two fragments and navigate between these two. Let’s open the Navigation Editor and click “New Destination”. In the dialog that appears, choose “Create blank destination” or if we already have created activity or fragment, we can choose them too. But for now, let’s create a blank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqmfQBnnFfjP1MDm9HaHkA.png" /></figure><p>Pick a name for the new fragment and click “Finish”. We can check the “Include fragment factory methods” and “Include interface callbacks?” if we need to. Then, our newly generated fragment will be displayed in the Navigation Editor. Let’s repeat this step to have another fragment to navigate into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lOLfduhax-ni7rElcPxlg.png" /></figure><p>After we have the second fragment, hover on the first fragment. There will be a circle on the right side of the fragment. Click it and drag to the second fragment. Now, we have the first fragment connected to the second one. If we click the arrow between these two fragments, we can see the action attribute on the right side of the Navigation Editor.</p><h3>Add Navigation Trigger</h3><p>Now, the movement between these two fragments should be triggered by something, right? To try this, let’s create a single button on the first fragment. Make it whatever we want, but pay attention to the button’s id.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>...<br>&gt;<br>  &lt;androidx.constraintlayout.widget.ConstraintLayout<br>      android:layout_width=&quot;match_parent&quot;<br>      android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;8dp&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:layout_marginEnd=&quot;8dp&quot;<br>        android:text=&quot;Go&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br>  &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/FrameLayout&gt;</pre><p>Next, we will invoke the navigation when the button is pressed by setting an on-click listener.</p><pre>// BlankFragment.kt<br>...<br>button.setOnClickListener {<br> it.findNavController().navigate(R.id.action_blankFragment_to_formFragment)<br>}<br>...</pre><p>So, what happen here? First, to invoke the navigation, we need to use the NavController class which we retrieve by calling findNavController. Then, we invoke the navigate method that receive resource id specifying the navigation action we want to run. This action id can be found by going to the Navigation Editor, clicking the arrow, and it will be available in Attributes pane. Now, if everything is good, we would have a nice transition between the first and second fragment when tapping the button.</p><p>That’s all for now. I’ll be covering how we might pass some parameters between navigation and how we tie the navigation trigger to other UI component such as bottom navigation in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c34f220232df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy App Using Docker]]></title>
            <link>https://medium.com/@habibridho/docker-as-deployment-tools-5a6de294a5ff?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a6de294a5ff</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Mon, 30 Apr 2018 02:05:42 GMT</pubDate>
            <atom:updated>2020-03-26T02:38:07.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*7s_0kd3huyTiHU9OE4nsCg.png" /><figcaption>src: <a href="https://spin.atomicobject.com/">https://spin.atomicobject.com</a></figcaption></figure><p>In this article, I will show you how we can deploy an application using docker. Without further ado, let’s write a simple Golang application for our sample case.</p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   &quot;net/http&quot;<br>   &quot;encoding/json&quot;<br>   &quot;fmt&quot;<br>)<br><br><strong>func </strong>main() {<br>   server := &amp;http.Server{<br>      Addr:&quot;:8888&quot;,<br>   }<br><br>   http.HandleFunc(&quot;/&quot;, hello)<br><br>   fmt.Println(&quot;Server started on port 8888&quot;)<br>   server.ListenAndServe()<br>}<br><br><strong>func </strong>hello(w http.ResponseWriter, _ *http.Request) {<br>   w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br>   payload := <strong>struct </strong>{<br>      Status  string  `json:&quot;status&quot;`<br>      Message string  `json:&quot;message&quot;`<br>   }{<br>      Status:&quot;Success&quot;,<br>      Message:&quot;Hello world!&quot;,<br>   }<br><br>   response, err := json.Marshal(payload)<br>   <strong>if </strong>err != nil {<br>      w.WriteHeader(http.<em>StatusInternalServerError</em>)<br>      <strong>return<br>   </strong>}<br><br>   w.Write(response)<br>}</pre><p>Now, we can build the app in our local machine and transfer the executable file to our server. Or, we can use docker to build it.</p><h4>Build</h4><p>To build using docker, we need to create a Dockerfile inside our project. This file consists a set of instructions to build a docker image. In this case, our Dockerfile will be like so.</p><pre><strong>FROM </strong>golang<br><strong>WORKDIR /</strong>go<strong>/</strong>src<strong>/</strong>github.com<strong>/</strong>habibridho<strong>/</strong>simple-go<br><strong>ADD </strong>. .<strong>/<br>RUN </strong>CGO_ENABLED=0 GOOS=linux go build <strong>-</strong>a <strong>-</strong>installsuffix .<br><strong>EXPOSE </strong>8888<br><strong>ENTRYPOINT </strong>.<strong>/</strong>simple-go</pre><p>So what happened here? First, we set our base image. We can use any docker image as our base, but it’s good to use an image that has everything you need to build your application. For example, if you are to build a NodeJS application, you might choose <a href="https://hub.docker.com/_/node/">nodejs image</a> for your base.</p><p>Next, we set our WORKDIR which will be used as base path for every command that use relative path. Then we ADD all our project files to the docker working directory. With all files already included, now we can RUN the build command. The EXPOSE command tells docker that the container created by this image will listen to the given port. Finally, we set the ENTRYPOINT of our container which is the executable produced by the build script.</p><pre>$ docker build -t simple-go .<br>$ docker run -d -p 8888:8888 simple-go</pre><p>Build your image and try to run it. If you successfully have your app running, then you are ready to deploy it on the server. Or is it?</p><h4>Multi Stage Build</h4><p>Let’s see the images that we have by running docker image ls</p><pre>REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE<br>simple-go           latest              d097fdad7838        43 seconds ago       808MB<br>golang              latest              6fe15d4cbc64        4 weeks ago          780MB</pre><p>Our image is really huge for a simple application. Though, it’s absolutely normal since we use the golang image as our base which by itself has 780MB of size. The question is: do we need all the things inside that image to run our app? No, since we build our app for Linux (see the RUN part of the Dockerfile), we should be able to run the executable file inside a basic linux distribution. And we will achieve that by editing our Dockerfile like so.</p><pre><strong>FROM </strong>golang as <em>builder<br></em><strong>WORKDIR /</strong>go<strong>/</strong>src<strong>/</strong>github.com<strong>/</strong>habibridho<strong>/</strong>simple-go<strong>/<br>COPY </strong>. .<strong>/<br>RUN </strong>CGO_ENABLED=0 GOOS=linux go build <strong>-</strong>a <strong>-</strong>installsuffix .<br><br><strong>FROM </strong>alpine:latest<br><strong>WORKDIR /</strong>app<strong>/<br>COPY --</strong>from=<em>builder </em><strong>/</strong>go<strong>/</strong>src<strong>/</strong>github.com<strong>/</strong>habibridho<strong>/</strong>simple-go<strong>/</strong>simple-go <strong>/</strong>app<strong>/</strong>simple-go<br><strong>EXPOSE </strong>8888<br><strong>ENTRYPOINT </strong>.<strong>/</strong>simple-go</pre><p>As we can see, we have two FROM statements which indicates we are not only using multiple base image, but also creating multiple stage of build. We name the first stage as builder which will be used as a referrer in the second stage. What we are doing here is simply copy the executable file created by builder stage, to the second stage. The result is a much smaller image that is ready to use in our server.</p><pre>REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE<br>simple-go           latest              26edf327a898        8 seconds ago       10.9MB</pre><h4>Deployment</h4><p>The next step is transferring our image to the server. We can use Docker Hub which is a docker repository server. We can push our image to the repository and pull it from the server.</p><pre>-- on local machine<br>$ docker tag simple-go habibridho/simple-go<br>$ docker push habibridho/simple-go</pre><pre>-- on server<br>$ docker pull habibridho/simple-go</pre><p>You have to note that the default docker repository visibility is public, so if your project is private, you need to change the project visibility from the Docker Hub website.</p><p>Alternatively, we can zip our image, transfer the file using scp, and import it in the server.</p><pre>-- on local machine<br>$ docker save -o image.zip simple-go<br>$ scp image.zip &lt;user&gt;@&lt;server-addres&gt;:&lt;target-location&gt;</pre><pre>-- on server<br>$ docker load -i &lt;path-to-image.zip&gt;</pre><p>Once we have the image in our server, we can run the app just like what we have done in our local machine.</p><pre>$ docker run -d -p 8888:8888 simple-go</pre><h4>Swarm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Aiq11bdY3qkYRTGN2CodAA.jpeg" /><figcaption>src: <a href="https://www.whalefree.com.au/">https://www.whalefree.com.au</a></figcaption></figure><p>The steps in the previous section is sufficient to make our app up and running, but we can go further. For example, we want to scale our app by creating three instances of it. We can re-run our previous command, use other port mapping, and implement a load balancer. But now, let’s do it the docker way.</p><p>First we need a compose file (I name it docker-compose.yml) which will tell docker what is the desired state of our app.</p><pre>version: &quot;3&quot;<br>services:<br>  api:<br>    image: simple-go<br>    deploy:<br>      replicas: 3<br>      resources:<br>        limits:<br>          cpus: &quot;0.1&quot;<br>          memory: 50M<br>    ports:<br>      - &quot;8887:8888&quot;<br>    networks:<br>      - host<br>networks:<br>  host:</pre><p>So here, we tell docker that we’re creating an api service using image named simple-go. Upon deployment, I want it to have 3 instances of the image and limit the app resources usage to 10% CPU usage and 50MB of memory. I also tell docker the port mapping (host’s 8887 to container’s 8888) and the network to use, in this case we will use the host’s networking stack.</p><p>We will utilise Docker’s swarm mode to deploy our app. So let’s init one.</p><pre>$ docker swarm init</pre><p>This will initialise a swarm manager that will manage our clustered app and do load balancing across available nodes. Now that we have a node available, let’s deploy our app.</p><pre>$ docker stack deploy -c docker-compose.yml simple-go</pre><p>If everything goes well, we should have 3 containers running.</p><pre>$ docker service ls<br>ID                  NAME                MODE                REPLICAS            IMAGE                   PORTS<br>mvmxjc1zk2ih        simple-go_api       replicated          3/3                 simple-go:latest        *:8887-&gt;8888/tcp</pre><pre>$ docker container ls<br>CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS               NAMES<br>e6101072bd54        simple-go:latest        &quot;/bin/sh -c ./simple…&quot;   10 minutes ago      Up 10 minutes       8888/tcp            simple-go_api.2.zbthwotfo9i9jixa1dizvzxvg<br>eef9d8dc9062        simple-go:latest        &quot;/bin/sh -c ./simple…&quot;   10 minutes ago      Up 10 minutes       8888/tcp            simple-go_api.3.aqh10lmx27pku3ld30m9t7a2o<br>03b5212c878b        simple-go:latest        &quot;/bin/sh -c ./simple…&quot;   11 minutes ago      Up 10 minutes       8888/tcp            simple-go_api.1.ovier6c3a6kqbwn62vfdmwwl0</pre><p>Now, let’s say we want to change the port mapping, or update the resource limit. We can just update the compose file and re-run the docker stack deploy command.</p><p>While this article has demonstrated how docker can be used for app deployment, there are still a lot of details that I omit here. Docker’s official documentation provides great explanation of the underlying concept, so I recommend you to check that out. Cheers!</p><ul><li><a href="https://docs.docker.com/engine/reference/builder/">Dockerfile reference</a></li><li><a href="https://docs.docker.com/develop/develop-images/multistage-build/">Multi-stage build</a></li><li><a href="https://docs.docker.com/compose/compose-file/">Compose file reference</a></li><li><a href="https://docs.docker.com/engine/swarm/key-concepts/#nodes">Swarm concept</a></li><li><a href="https://docs.docker.com/engine/swarm/how-swarm-mode-works/services/">Service concept</a></li></ul><p><a href="https://medium.com/@habibridho/how-to-easily-setup-wordpress-using-docker-a798081dc577"><em>Checkout this tutorial to setup Wordpress with Docker.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a6de294a5ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock React Native Dimensions]]></title>
            <link>https://medium.com/amartha-engineering/mock-react-native-dimensions-1e34987a5ff3?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e34987a5ff3</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 03:34:44 GMT</pubDate>
            <atom:updated>2018-03-06T03:40:53.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTlLMggdjx6uLyHicPAdqg.png" /></figure><p>React Native (RN) is a great tool for developing mobile application and Jest to me is a really straightforward testing tool for it. If you are yet to use Jest to test your RN app, I recommend you to read <a href="https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe">this article</a> to get a picture of how good it is.</p><p>Everything is good with Jest and me, testing my component’s functions, testing actions and reducer, taking snapshots, etc. Until I test a component that use RN’s Dimensions API.</p><pre>// MyComponent.js<br>import React, { Component } from &quot;react&quot;<br>import { Dimensions, Text, View } from &quot;react-native&quot;<br>...<br>const { width, height } = Dimensions.get(&quot;screen&quot;)</pre><pre>class MyComponent extends Component {<br>  ...<br>  render() {<br>    //use the width and height somewhere here<br>    ...<br>  }<br>}</pre><pre>export default MyComponent</pre><pre>// MyComponent.test.js<br>import React from &quot;react&quot;<br>import MyComponent from &quot;./MyComponent&quot;</pre><pre>test(&quot;MyComponent default render&quot;, () =&gt; {<br>  const component = renderer.create(&lt;MyComponent/&gt;)<br>  let tree = component.toJSON()<br>  expect(tree).toMatchSnapshot()<br>})</pre><p>I run the test and it failed because:</p><pre>Invariant Violation: No dimension set for key screen</pre><p>However, if I change the dimensions type from screen to window the test would succeed. So it seems theDimensions API is not mocked entirely in the RN version that I used.</p><h4>Manual Mock</h4><p>Here is where manual mock comes into play. The first thing to do is defining the mock itself. I create a folder named __mocks__ which adjacent to my node_modules folder and make a mock file Dimensions.js .</p><pre>// Dimensions.js inside __mocks__ folder<br>&quot;use strict&quot;;</pre><pre>const Dimensions = {<br>  get: jest.fn().mockReturnValue({width: 100, height:100})<br>}</pre><pre>module.exports = Dimensions</pre><p>And in my test file:</p><pre>// MyComponent.test.js<br>...<br>jest.mock(&quot;Dimensions&quot;)<br>import MyComponent from &quot;./MyComponent&quot;</pre><pre>...</pre><p>What I do here is telling jest module system to use mockedDimensions that I created instead of the one from the react-native module. By doing this, we can test our component without touching the real implementation of Dimensions API. This method could also be useful if we got another API or Component inside our tested component that need to be mocked.</p><p><a href="https://amartha.com/id_ID/careers/"><em>We’re always looking for awesome people to join our incredible journey! Click here to learn more!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e34987a5ff3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amartha-engineering/mock-react-native-dimensions-1e34987a5ff3">Mock React Native Dimensions</a> was originally published in <a href="https://medium.com/amartha-engineering">Amartha Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Collapsing Toolbar Using React Native]]></title>
            <link>https://medium.com/@habibridho/implementing-collapsing-toolbar-using-react-native-4a84e1718f11?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a84e1718f11</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[animated-api]]></category>
            <category><![CDATA[collapsing-toolbar]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Sun, 11 Feb 2018 11:22:04 GMT</pubDate>
            <atom:updated>2018-02-11T11:22:04.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Collapsing toolbar is really cool, both visually and in user experience point of view. We can start with initial view with huge header, giving the user a bit of context, then collapsing it when the user start scrolling the content, giving her the screen real estate to enjoy the page’s content. In this article, I will explore how we can achieve that using React Native.</p><h4>View Structure</h4><p>Let’s start with a very simple view structure. We will have a header that we will collapse and a ScrollView that will contain our long content.</p><pre>import React, { Component } from &#39;react&#39;;<br>...<br>import content from &#39;./content&#39;;</pre><pre>export default class App extends Component {<br>  render(){<br>    return(<br>      &lt;View style={styles.container}&gt;<br>        &lt;View style={{height: 300}}/&gt;<br>          &lt;ScrollView contentContainerStyle={styles.scrollContainer}&gt;<br>            &lt;Text style={styles.title}&gt;This is Title&lt;/Text&gt;<br>            &lt;Text style={styles.content}&gt;{content}&lt;/Text&gt;<br>          &lt;/ScrollView&gt;<br>      &lt;/View&gt;<br>    )<br>  }<br>}</pre><pre>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1<br>  },<br>  scrollContainer: {<br>    padding: 16<br>  }, <br>  title: {<br>    fontSize: 24,<br>    marginVertical: 16<br>  }<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1kacfTpe5bQcJAzFOT6nhA.gif" /></figure><p>Our first attempt doesn’t look so good as the header stays where it is. So, we will make the height changes as we scroll the content up using RN’s Animated library.</p><h4>Animated and onScroll Combination</h4><p>The Animated library provides several useful APIs to create an animation, but we will focus on the event and interpolate method. The event method can map scrolling events into animated values. We will then calculate the header’s height based on these values using the interpolate method.</p><pre>...<br>const HEADER_EXPANDED_HEIGHT = 300<br>const HEADER_COLLAPSED_HEIGHT = 60</pre><pre>export default class App extends Component {<br>  constructor() {<br>    super()<br>    this.state = {<br>      scrollY: new Animated.Value(0)<br>    }<br>  }</pre><pre>  render() {<br>    const headerHeight = this.state.scrollY.interpolate({<br>      inputRange: [0, HEADER_EXPANDED_HEIGHT-HEADER_COLLAPSED_HEIGHT],<br>      outputRange: [HEADER_EXPANDED_HEIGHT, HEADER_COLLAPSED_HEIGHT],<br>      extrapolate: &#39;clamp&#39;<br>    })</pre><pre>    return(<br>      &lt;View style={styles.container}&gt;<br>        &lt;Animated.View style={{height: headerHeight}}/&gt;<br>          &lt;ScrollView<br>            contentContainerStyle={styles.scrollContainer}<br>            onScroll={Animated.event(<br>              [{ nativeEvent: {<br>                   contentOffset: {<br>                     y: this.state.scrollY<br>                   }<br>                 }<br>              }])}<br>            scrollEventThrottle={16}&gt;<br>            ...<br>          &lt;/ScrollView&gt;<br>      &lt;/View&gt;<br>    )<br>  }<br>}</pre><p>We subscribe Animated.event to the onScroll event of our ScrollView component. This will assign a new value to the scrollY state every time the scrolling event fired, thus invoking a re-render.</p><p>The scrollY value will be mapped into headerHeight value using the interpolate method. In the above example, we are only interested in the scrolling event in the area between the expanded and the collapsed header height. Thus, scrolling beyond those area would not affect our header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*0AOJqhvnUP1buQk5e86ZgA.gif" /></figure><p>Now, we have a collapsing header. However, it’s a little bit off since the content scroll right away without waiting the header collapse completely. In order to fix it, we will set the header’s position as absolute and set a top padding of the ScrollView equal to height of the expanded header.</p><pre>const { width: SCREEN_WIDTH } = Dimensions.get(&#39;screen&#39;)<br>...<br>return(<br>  &lt;View style={styles.container}&gt;<br>    &lt;Animated.View style={{height: headerHeight, width: SCREEN_WIDTH, position: &#39;absolute&#39;, top: 0, left: 0}}/&gt;<br>      &lt;ScrollView<br>        contentContainerStyle={{padding: 16, paddingTop: HEADER_EXPANDED_HEIGHT}}<br>        ...&gt;<br>            ...<br>      &lt;/ScrollView&gt;<br>  &lt;/View&gt;)<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*yH5gs3a79vfLEyhdKKeW2g.gif" /></figure><p>Using the same basic principle of animating the header, we could animate other things inside the header.</p><pre>...<br>render() {<br>  ...<br>  const headerTitleOpacity = this.state.scrollY.interpolate({<br>    inputRange: [0, HEADER_EXPANDED_HEIGHT-HEADER_COLLAPSED_HEIGHT],<br>    outputRange: [0, 1],<br>    extrapolate: &#39;clamp&#39;<br>  });</pre><pre>  const heroTitleOpacity = this.state.scrollY.interpolate({<br>    inputRange: [0, HEADER_EXPANDED_HEIGHT-HEADER_COLLAPSED_HEIGHT],<br>    outputRange: [1, 0],<br>    extrapolate: &#39;clamp&#39;<br>  });</pre><pre>return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;Animated.View style={[styles.header, { height: headerHeight }]}&gt;<br>        &lt;Animated.Text style={{textAlign: &#39;center&#39;, marginTop: 28, opacity: headerTitleOpacity}}&gt;{headerTitle}&lt;/Animated.Text&gt;<br>        &lt;Animated.Text style={{position: &#39;absolute&#39;, bottom: 16, left: 16, opacity: heroTitleOpacity}}&gt;{headerTitle}&lt;/Animated.Text&gt;<br>      &lt;/Animated.View&gt;<br>      ...<br>    &lt;/View&gt;<br>  )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*iAgejXPMeA-c60V2_vW8xg.gif" /></figure><p><em>You can access the full code </em><a href="https://github.com/habibridho/RNCollapsingToolbar"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a84e1718f11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing Business Logic Between Web and Mobile App Using React]]></title>
            <link>https://medium.com/@habibridho/sharing-business-logic-between-web-and-mobile-app-using-react-b0e5e91cb7c2?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0e5e91cb7c2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 05:21:13 GMT</pubDate>
            <atom:updated>2017-11-26T05:21:13.723Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need to create both web app and mobile app with identical functionality, then sharing the same business logic between those apps should be really tempting. And thanks to React, we are able to do that.</p><p>First, we need to setup the project to support our intention. I think it would be easier to start from a react native (RN) project because it already has Android and iOS configuration and we can copy some couple things from React project.</p><pre>$ react-native init ReactUniversal --version 0.49.0</pre><p>After the initialisation finished, we create and src folder to place all our code. Rename the default index.js file to index.mobile.js and move it to the src folder we’ve created. Then, create index.js file or simply copy it from a fresh React project. The plan is we will use index.js for the web entry point while index.mobile.js for the mobile.</p><p>Next, we need to tell the native code where to find the js bundle so edit both MainApplication.java and AppDelegate.m</p><pre>// MainApplication.java<br>...<br>@Override<br>protected String getJSMainModuleName() {<br>  return &quot;src/index.mobile&quot;;<br>}<br>...</pre><pre>// AppDelegate.m<br>...<br>jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@&quot;src/index.mobile&quot; fallbackResource:nil];<br>...</pre><p>We also need to update package.json like so, so that the project can support both web and mobile platform.</p><pre>...<br>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node node_modules/react-native/local-cli/cli.js start&quot;,<br>  &quot;test&quot;: &quot;jest&quot;,<br>  &quot;start-web&quot;: &quot;react-scripts start&quot;,<br>  &quot;test-web&quot;: &quot;react-scripts test --env=jsdom&quot;<br>},<br>&quot;dependencies&quot;: {<br>  &quot;react&quot;: &quot;16.0.0-beta.5&quot;,<br>  &quot;react-native&quot;: &quot;0.49.0&quot;,<br>  &quot;react-dom&quot;: &quot;^16.1.1&quot;,<br>  &quot;react-scripts&quot;: &quot;1.0.17&quot;<br>},<br>&quot;devDependencies&quot;: {<br>  &quot;babel-jest&quot;: &quot;21.2.0&quot;,<br>  &quot;babel-preset-react-native&quot;: &quot;4.0.0&quot;,<br>  &quot;jest&quot;: &quot;21.2.1&quot;,<br>  &quot;react-test-renderer&quot;: &quot;16.0.0-beta.5&quot;<br>},<br>&quot;jest&quot;: {<br>  &quot;preset&quot;: &quot;react-native&quot;<br>}<br>...</pre><p>What we do here is simply adding React dependencies such as react-dom and react-scripts to our project. At this point, we should be able to run both React and RN from this project.</p><pre># running RN<br>$ react-native run-ios</pre><pre># running React<br>$ npm run start-web</pre><p><a href="https://github.com/habibridho/ReactUniversal/tree/initial-setup">habibridho/ReactUniversal</a></p><p>Now that we have successfully combine these two libraries, we will start to write the redux parts. Just to make things organised, let’s create a redux folder inside our src and place our action and reducer there.</p><pre>// redux/action.js<br>export const ACTION_TYPES = {<br>  ADD: &quot;ADD&quot;,<br>  SUBSTRACT: &quot;SUBSTRACT&quot;<br>}</pre><pre>export function add() {<br>  return {<br>    type: ACTION_TYPES.ADD<br>  }<br>}</pre><pre>export function substract() {<br>  return {<br>    type: ACTION_TYPES.SUBSTRACT<br>  }<br>}</pre><pre>// redux/reducer.js<br>import { createStore } from &quot;redux&quot;<br>import { ACTION_TYPES } from &quot;./action&quot;</pre><pre>const initialState = {<br>  number: 0<br>}</pre><pre>function reducer(state = initialState, action) {<br>  switch(action.type) {<br>    case ACTION_TYPES.ADD:<br>      return {<br>        ...state,<br>        number: state.number + 1<br>    }<br>    case ACTION_TYPES.SUBSTRACT:<br>      return {<br>        ...state,<br>        number: state.number - 1<br>      }<br>    default:<br>      return state<br>    }<br>}</pre><pre>let store = createStore(reducer)<br>export default store</pre><p>And of course, we need to wrap our root component, both in web and mobile.</p><pre>// src/index.js<br>...<br>import { Provider } from &#39;react-redux&#39;<br>import store from &quot;./redux/reducer&quot;</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>, document.getElementById(&#39;root&#39;));<br>...</pre><pre>// src/index.mobile.js<br>...<br>import React, { Component } from &quot;react&quot;<br>import { Provider } from &#39;react-redux&#39;<br>import store from &quot;./redux/reducer&quot;</pre><pre>class Root extends Component {<br>  render() {<br>    return (<br>      &lt;Provider store={store}&gt;<br>        &lt;App/&gt;<br>      &lt;/Provider&gt;<br>    )<br>  }<br>}</pre><pre>AppRegistry.registerComponent(&#39;ReactUniversal&#39;, () =&gt; Root);</pre><p><a href="https://github.com/habibridho/ReactUniversal/tree/setup-redux">habibridho/ReactUniversal</a></p><p>The last part, we will edit the UI and utilise the actions we’ve created.</p><pre>// src/web/App.js<br>...<br>import { connect } from &quot;react-redux&quot;<br>import { add, substract } from &quot;../redux/action&quot;</pre><pre>class App extends Component {<br>  ...<br>  render() {<br>    return (<br>      ...<br>      &lt;p className=&quot;App-intro&quot;&gt;<br>        { this.props.number }<br>      &lt;/p&gt;<br>      &lt;button onClick={this.props.substract}&gt;Substract&lt;/button<br>      &lt;button onClick={this.props.add}&gt;Add&lt;/button&gt;<br>      ...<br>     )<br>  }<br>}</pre><pre>export default connect(<br>  state =&gt; ({ number: state.number }),<br>  { add, substract }<br>)(App)</pre><pre>// src/mobile/App.js<br>...<br>import { connect } from &quot;react-redux&quot;<br>import { add, substract } from &quot;../redux/action&quot;</pre><pre>class App extends Component&lt;{}&gt; {<br>  render() {<br>    return (<br>      &lt;View style={styles.container}&gt;<br>        &lt;Text style={styles.welcome}&gt;Number&lt;/Text&gt;<br>        &lt;Text style={styles.instructions}&gt;<br>          { this.props.number }<br>        &lt;/Text&gt;<br>        &lt;Button<br>          title=&quot;Add&quot;<br>          onPress={this.props.add}<br>        /&gt;<br>        &lt;Button<br>          title=&quot;Substract&quot;<br>          onPress={this.props.substract}<br>        /&gt;<br>      &lt;/View&gt;<br>    )<br>  }<br>}<br>...<br>export default connect(<br>  state =&gt; ({number: state.number}),<br>  { add, substract }<br>)(App)</pre><p><a href="https://github.com/habibridho/ReactUniversal/tree/ui-integration">habibridho/ReactUniversal</a></p><p>Having a shared business logic is really handy. Imagine if you got a complex logic, then you’ll have save a lot of time by writing it once. Catch a bug? One fix and you will have it fixed for both web and mobile.</p><p>Maybe, we can go a bit further by not only sharing the business logic, but also the UI. That should be the same as how RN render differently between Android and iOS by mapping the JSX to the respective native component. I’m not a fan of this idea though, because web and mobile have different experience. But if you have a little time and just a few developers, anything will do right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e5e91cb7c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript ES7 Async Await Tutorial]]></title>
            <link>https://medium.com/@habibridho/javascript-es7-async-await-tutorial-64275c81ce2e?source=rss-9010b5273d08------2</link>
            <guid isPermaLink="false">https://medium.com/p/64275c81ce2e</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Habib Ridho]]></dc:creator>
            <pubDate>Sun, 17 Sep 2017 08:34:48 GMT</pubDate>
            <atom:updated>2017-09-17T08:34:48.596Z</atom:updated>
            <content:encoded><![CDATA[<p>We have seen for a long time how Promises save us from callback hell. Nowadays, we got async-await which could polish our code so that it won’t hurt our teammate’s eyes.</p><h3>Example Case</h3><p>Suppose we want to retrieve a country code from an API so that we can query the country phone code using another API. Easy right? You may think that it only requires chaining two Promises. But to make thing worse in this case, let’s use fetch so we need to parse it into JSON format, which means, another Promises! Yeay?</p><h3>Using Promises</h3><p>First, let’s make our code using standard Promises like so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9403b75f3f4c2318b2c6702cd2781cb1/href">https://medium.com/media/9403b75f3f4c2318b2c6702cd2781cb1/href</a></iframe><p>It’s pretty good, no? But, let’s make it better.</p><h3>Using Async Await</h3><p>The same function using async-await syntax would be as follow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0244c6a82d97c32f8ad54e30c48ecb8a/href">https://medium.com/media/0244c6a82d97c32f8ad54e30c48ecb8a/href</a></iframe><p>We save 5 lines of code! But that’s not really a big deal. The amazing thing is that how our code become cleaner and how it kinda feel like a synchronous one.</p><p>Some important notes, the await could only be used inside an async function. The async function itself is actually a Promise, so you should do something like this when using it.</p><pre>async function getCountries() {<br>  ...<br>  let json2 = await res2.json()<br>  return json2[code]<br>}</pre><pre>getCountries().then(function(result){<br>  console.log(result)<br>})</pre><p><em>You could try this tutorial by cloning the code from </em><a href="https://github.com/habibridho/async-await-tutorial"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64275c81ce2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>