<?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[Ruangguru Engineering - Medium]]></title>
        <description><![CDATA[We are the pioneers of education technology in Indonesia. As the biggest tech-enabler in this industry, we break the status quo and show the importance of big data, personalized outcome analysis, and mobile-based learning as the future of modern education. - Medium]]></description>
        <link>https://medium.com/ruangguru-engineering?source=rss----2c3b1fdf5d48---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Ruangguru Engineering - Medium</title>
            <link>https://medium.com/ruangguru-engineering?source=rss----2c3b1fdf5d48---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:40:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ruangguru-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Song of Praise to MvRx]]></title>
            <link>https://medium.com/ruangguru-engineering/a-song-of-praise-to-mvrx-3ab0e47e6699?source=rss----2c3b1fdf5d48---4</link>
            <guid isPermaLink="false">https://medium.com/p/3ab0e47e6699</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[mvrx]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvi]]></category>
            <dc:creator><![CDATA[Indri Yunita]]></dc:creator>
            <pubDate>Fri, 31 Jan 2020 10:43:03 GMT</pubDate>
            <atom:updated>2020-02-14T03:22:51.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RL6HBynjVmSH1EPdDf8qeQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fifernando">Fidel Fernando</a> / <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>One-Way All the Way</h3><p>I guess by now we can all agree that unidirectional (one-way) data flow has a big role in creating a reliable presentation layer. Just to make sure we are on the same page, unidirectional data flow is a technique of applying one-way mutations on an immutable data state. In this pattern, mutations can only be done outside the presentation/view, while presentation/view is made to be dumb (stateless), only passively waiting to be notified when some state changes occur. This concept was mainly popularized by <a href="https://en.wikipedia.org/wiki/Redux_(JavaScript_library)">Redux</a>, and most commonly used alongside with <a href="https://en.wikipedia.org/wiki/React_(JavaScript_library)">React</a>.</p><p>Current trend shows that the concept has been adopted in Android development as well, although more commonly known as MVI (<strong>Model-View-Intent)</strong> architecture pattern in the Android world. Several frameworks built by established enterprises based on this pattern for example are <a href="https://github.com/airbnb/MvRx"><strong>MvRx</strong></a> by AirBnb, <a href="https://github.com/spotify/mobius"><strong>Mobius</strong></a> by Spotify, <a href="https://github.com/Tinder/StateMachine"><strong>StateMachine</strong></a> by Tinder, and <a href="https://github.com/badoo/MVICore"><strong>MVICore</strong></a> by Badoo.</p><p>Several months ago, we at Ruangguru decided that we needed this approach in our Android app (well, it’s a long-overdue action but I’m just glad we took it anyway). So we looked into the options, and MvRx quite stood up because of its maturity and excellency of the <a href="https://github.com/airbnb/MvRx/wiki">documentation</a>. Also, it relies heavily on RxJava, a library that we’ve been using extensively already. After looking into the example project and making a PoC based on an actual feature in our app, we were sold.</p><p>As a side note, at some point our discussion also touched the issue of how we should use reusable and composable UI components and whether Airbnb’s <a href="https://github.com/airbnb/epoxy">Epoxy</a> library would suit our needs. After some thinking and discussions, we decided it would not be worth it as the steps we would need to take would be huge. And with Jetpack Compose’s bright promise in the future, we thought we would just wait until Jetpack Compose is ready to be used in production.</p><p>Back to MvRx. Actually I’m kind of disappointed that I don’t find too many references of MvRx on the Internet. Or rather, I’m surprised it doesn’t get enough praise that it deserves. So consider this post that, a praise to MvRx for making Android development a little less of a pain in the a** :D</p><h3>Benefits</h3><p>What does that mean for us in concrete terms?</p><ul><li>First off, since we made the change from the MVP pattern, where the View and the Presenter communicates through a contract interface, it means with MvRx we now don’t need to write it anymore (and yes, it gets tedious over time). So that means one less file to write :)</li><li>Secondly, by wrapping all the properties necessary to render a screen in a MvRxState, it makes it easier to scan over them. What we encountered before, what with less clear boundary between States and View, States often found their way to reside in View (e.g. Fragment) instead of residing strictly in Presenter. This is marked by the existence of instance variables representing States in said Fragment, all cluttered and headache-inducing. Some tip based on our experience: putting MvRxState in its own file (parallel with its Fragment and ViewModel files) makes it all the cleaner.</li><li>MvRx is lifecycle aware, because it’s built respecting Jetpack’s LifecycleOwner. That means we don’t have to manually handle subscriptions ourselves. We used to have to dispose CompositeDisposable in Presenter whenever view is detached (through some “onViewDetached()” callback stated in the contract. Now with MvRxViewModel, we kissed it goodbye because it uses CompositeDisposable that’s automatically disposed in onCleared. Also, in the MvRxView, invalidate function — where you’re supposed to handle UI according to state changes — is only called when current View’s lifecyle is at least STARTED (that means STARTED and RESUMED).</li><li>savedInstanceState<strong> </strong>made easy by @PersistStateannotation.</li></ul><h3>Some Things to Considerate</h3><p>Besides that, I’d like to recap some things for consideration based on our experience migrating to MvRx.</p><ul><li>As MvRx is Fragment-based, you should put your feature code inside Fragments. So if you’re not doing that already, you should be willing to make that change.</li><li>Choose the scope of your ViewModel wisely. MvRxViewModel can be Fragment-scoped or Activity-scoped. When you need to share your States across multiple Fragments, use Activity-scoped ViewModel. One scenario where you might want to share your states, for example, is when you have a screen containing list in Fragment A, and when an item is clicked it will lead to a detail screen in Fragment B.</li></ul><pre>// Activity-scoped<br>private val viewModel: SomeActivityViewModel by <em>activityViewModel</em>()</pre><pre>// Fragment-scoped<br>private val viewModel: SomeFragmentViewModel by fragment<em>ViewModel</em>()</pre><ul><li>It’s mostly enough that you implement invalidate in the Fragment and handle all operations of updating UI based on state changes there, but sometimes you might want to subscribe to state changes manually. MvRx provides three subscription methods to create your own subscriptions: subscribe() ,selectSubscribe(), and asyncSubscribe. One common parameter for these functions is deliveryMode: DeliveryMode, which is a sealed class with two subclasses: <strong>RedeliverOnStart</strong> (the default mode), and <strong>UniqueOnly</strong>. From the Kotlin code documentation:</li></ul><pre><em>* </em><strong><em>@param </em></strong><em>deliveryMode If [UniqueOnly], when this MvRxView goes from a stopped to start lifecycle a state value<br>* will only be emitted if the state changed. This is useful for transient views that should only<br>* be shown once (toasts, poptarts), or logging. Most other views should use false, as when a view is destroyed<br>* and recreated the previous state is necessary to recreate the view.</em></pre><p>For example, if I want to subscribe to an event where user reports on some content, which will show Toast when the request is successful and handle error when it happens, I would write the following:</p><pre>viewModel.<em>asyncSubscribe</em>(<br>    SomeState::contentReportAsync,<br>    uniqueOnly(),<br>    <strong>{ </strong>handleError(<strong>it</strong>) <strong>}</strong>,<br>    <strong>{ </strong><em>activity</em>?.<em>showToast</em>(R.string.<em>msg_content_reported</em>) <strong>}<br></strong>)</pre><h3>Conclusion</h3><p>Was the migration seamless? No. It took some time to get the hang of it, especially converting from imperative coding style. Was it worth it though? Hell yes. We could see that our code is cleaner and has better separation of concerns now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ab0e47e6699" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ruangguru-engineering/a-song-of-praise-to-mvrx-3ab0e47e6699">A Song of Praise to MvRx</a> was originally published in <a href="https://medium.com/ruangguru-engineering">Ruangguru Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Coroutine LiveData in ViewModel]]></title>
            <link>https://medium.com/ruangguru-engineering/how-to-coroutine-livedata-in-viewmodel-6def66f932a7?source=rss----2c3b1fdf5d48---4</link>
            <guid isPermaLink="false">https://medium.com/p/6def66f932a7</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[heri sulistiyanto]]></dc:creator>
            <pubDate>Mon, 11 Nov 2019 03:15:08 GMT</pubDate>
            <atom:updated>2019-11-11T03:15:08.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfvBXuaE0jJ5hXFqmR9mFQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rami_alzayat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rami Al-zayat</a> on <a href="https://unsplash.com/s/photos/android?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As we know lately . . Kotlin Coroutine become <em>hot topic</em> in Android development. Usually i’m using RxJava in my Android project, and i decide to take a look on Coroutine for a simple project and share my “<em>experience”</em> in this story.</p><p>I’m using Retrofit (2.6.1) in my demo project, which already support for suspend function. Let’s take a look in my MovieApiService below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1523e4572b99926814100a2bd4e895ce/href">https://medium.com/media/1523e4572b99926814100a2bd4e895ce/href</a></iframe><p>From the snippet above, we see that all of the function return object Retrofit Response not Deferred.</p><p>And then, i have a BaseDataSource which is the base abstract class for the DataSource, and here’s the snippet code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51d100fed169fd6d7234ce50ae85f97/href">https://medium.com/media/a51d100fed169fd6d7234ce50ae85f97/href</a></iframe><p>This BaseDataSource, we wrap the Retrofit Response into 2 type in the getResult function, ResponseResult.Success and ResponseResult.Error.</p><p>In resultLiveData function, we gonna wrap the suspend function result as LiveData by emitting the object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6d55a14c1f0d28e1bb709c82d75ca6d/href">https://medium.com/media/d6d55a14c1f0d28e1bb709c82d75ca6d/href</a></iframe><p>Take a look on snippet above. Both of function will return LiveData using the function from the BaseDataSource. So when those function invoked, it should give LiveData immediately right? <em>ummmm</em> . . . not quite right though.</p><p>So here’s my experience i mentioned earlier.</p><p>Usually, when we work using ViewModel &amp; LiveData, we put like . . . let say 2 variable which will store value to be observe :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9783077c45e150ea8666635695919877/href">https://medium.com/media/9783077c45e150ea8666635695919877/href</a></iframe><p>On the snippet above will give null result when we observe movieResult . . but why?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*gVUNtBlqasnWBPQM1XlzJg.jpeg" /><figcaption>But why??</figcaption></figure><p>So it seem our DataSource won’t emitting data because the LiveData (<em>from our remote data source</em>) mark as no active observer. And then i change the approach, for the function in our <em>viewmodel</em> become not return Unit but return LiveData instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c9ccba95aaab3d3aa806eb322f6726/href">https://medium.com/media/80c9ccba95aaab3d3aa806eb322f6726/href</a></iframe><p>When we observe the LiveData by observing discoverAllMovies() in our Activity, it will give correct result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7035d5fbdc9a9f49a235801ee0ad442f/href">https://medium.com/media/7035d5fbdc9a9f49a235801ee0ad442f/href</a></iframe><p>Please take a look at :</p><pre>dashboardViewModel.discoverAllMovies().<em>onResult </em><strong>{<br>    </strong>vfDashboardContent.<em>displayedChild </em>= when(<strong>it</strong>) {<br>        is ResponseResult.Success -&gt; {<br>            val data = it.result.data?.mapToMovieItemList()<br>            movieAdapter.setListMovieData(data)<br>            DashboardStateView.STATE_CONTENT<br>        }<br>        is ResponseResult.Loading -&gt; {<br>            DashboardStateView.STATE_LOADING<br>        }<br>        is ResponseResult.Error -&gt; {<br>            tvCommonError.<em>text </em>= <strong>it</strong>.msg.errorMsg.<em>orEmpty</em>()<br>            DashboardStateView.STATE_ERROR<br>        }<br>    }<br><strong>}</strong></pre><p>On above block, the live data can be observed (not null) and result will be handled by the state, then update current UI.</p><p>After this demo project, i realise that the livedata{} on coroutine need to be observe directly, so it can emitting data.</p><p>You can find the full source code in my <a href="https://github.com/herisulistiyanto/Simple-Retrofit-Coroutine">github</a>.</p><p><a href="https://github.com/herisulistiyanto/Simple-Retrofit-Coroutine">herisulistiyanto/Simple-Retrofit-Coroutine</a></p><p>If you find this article helpful, please give your warmest clap :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUW_wXKWPOaYudPM3RSFgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@peet818?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pete Pedroza</a> on <a href="https://unsplash.com/s/photos/thank-you?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6def66f932a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ruangguru-engineering/how-to-coroutine-livedata-in-viewmodel-6def66f932a7">How to Coroutine LiveData in ViewModel</a> was originally published in <a href="https://medium.com/ruangguru-engineering">Ruangguru Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips on Unit Testing In Android with Kotlin]]></title>
            <link>https://medium.com/ruangguru-engineering/tips-on-unit-testing-in-android-with-kotlin-d8d70beff401?source=rss----2c3b1fdf5d48---4</link>
            <guid isPermaLink="false">https://medium.com/p/d8d70beff401</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[junit4]]></category>
            <dc:creator><![CDATA[Indri Yunita]]></dc:creator>
            <pubDate>Tue, 15 Oct 2019 11:48:27 GMT</pubDate>
            <atom:updated>2020-01-06T02:45:49.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLkVUaQ0XnWUTFS7Nkpzwg.jpeg" /></figure><p>Hello! Today I’d like to talk about some tips on unit testing in Android with Kotlin. Some of them may have more to do with unit testing in general, which for the most part are related to how to create such “flow” and cutting down on unnecessary things, a.k.a productivity tips.</p><p>As for the unit testing framework, JUnit 5 has been out for a while now and there have been numerous talks about how you should adopt it, but JUnit 4 has been the standard for the longest time. In this article, I’m using JUnit 4.</p><h4>Setup</h4><p>A little setup in app-level build.gradle:</p><pre>dependencies {<br>    testImplementation ‘junit:junit:4.12’<br>    testImplementation ‘org.mockito:mockito-core:2.25.0’<br>}</pre><p>The <strong>junit</strong> part by default is there when you create a new project, but we need to add mockito dependency by ourselves. Now, we <em>could</em> do unit testing without Mockito. It’s <em>just</em> a framework to help us creating mocks as replacements for dependencies in our project. Mock itself is just one kind of replacement among several others. Which brings us to the next part.</p><h4>Know Your Test Doubles</h4><p>A unit test should test functionality in isolation. Any external dependencies not related with the system under test should be replaced and conditioned to create a “controlled environment”. In the world of unit testing, this replacement has an umbrella term: <strong><em>test double</em></strong><em>.</em> Now there has been some common confusion around the term. Some people say “mock” when they mean “test double” in general. Meanwhile, test double comprises:</p><ol><li><em>Dummy object, </em>when it’s passed around but its methods are never called. It doesn’t have behavior.</li></ol><p>2. <em>Fake, </em>is an object that has working implementations but not the same as production ones, usually, are simplified. One common example is when you implement a Repository using in-memory implementation.</p><p>3. <em>Stub, </em>is an object that has a partial implementation to an interface or class. It is there to satisfy some limited needs and usually, the implementation or behavior is predetermined.</p><p>4. <em>Mock, </em>is the kind of test double you have to set up with expectations.</p><p>Further reading on this subject:</p><ul><li><a href="https://stackoverflow.com/questions/3459287/whats-the-difference-between-a-mock-stub">What&#39;s the difference between a mock &amp; stub?</a></li><li><a href="https://medium.com/@CDehning/when-to-use-fakes-instead-of-mocks-c80188b9a3f1">When to use Fakes instead of Mocks</a></li></ul><h4>Test Method Naming</h4><p>Best practice for the naming test method in Kotlin is to put method names in between backticks and use space between words. For example:</p><pre>@Test<br>fun `update username success user is cached`() { ... }</pre><p>This, arguably, improves the readability. But, I personally like the Java tradition better, that is <strong>methodName_stateUnderTest_expectedBehavior</strong>, because there is clear distinction between the roles of elements in the name<strong>. </strong>The above test method then becomes:</p><pre>@Test<br>fun updateUsername_success_userCached() { ... }</pre><h4>Mockito Kotlin</h4><p>Look at the test code below:</p><pre>import org.mockito.ArgumentCaptor</pre><pre>...</pre><pre>@Test<br>fun updateUsername_success_userCached() {<br>    ...<br>    <strong>ArgumentCaptor.forClass(User::class.<em>java</em>)</strong>.<em>apply </em><strong>{<br><br>        </strong>SUT.updateUsername(userId = USER_ID, username = USER_NAME)<br>  <br>        <strong>verify(usersCacheMock).cacheUser(capture())<br> </strong>       val cachedUser = firstValue<br>        assertThat(cachedUser.userId, `is`(USER_ID))<br>        assertThat(cachedUser.username, `is`(USER_NAME))<br>    <strong>} </strong><br>}</pre><p>When you run the test, it throws error “<em>java.lang.IllegalStateException: ac.capture() must not be null</em>”. It’s because I have specified “user” in “cacheUser” to be non-nullable, while “ac.capture()” returns null. To tackle this, some fine guy named Niek Haarman created a helper library, <a href="https://github.com/nhaarman/mockito-kotlin">Mockito-Kotlin</a>. To add the dependency, add this:</p><pre>testImplementation &quot;com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0&quot;</pre><p>Then you just have to replace Mockito’s default implementation for ArgumentCaptorwith Mockito-Kotlin’s. The above test method then becomes:</p><pre>import com.nhaarman.mockitokotlin2.argumentCaptor</pre><pre>...</pre><pre>@Test<br>fun updateUsername_success_userCached() {<br>    <em>...<br>    </em><strong><em>argumentCaptor</em>&lt;User&gt;().<em>apply </em>{<br></strong><br>    <strong>}<br>}</strong></pre><p><em>Et voila! T</em>he test runs without error.</p><h4>State All Test Cases Before Writing Tests</h4><p>It’s a good habit to write all possible test cases that come to mind before you start writing tests. For example, the requirements for fetching user are below:</p><blockquote><em>1) If the user with given user ID is not in the cache then it should be fetched from the server.<br>2) If the user fetched from the server then it should be stored in the cache before returning to the caller.<br>3) If the user is in the cache then cached record should be returned without polling the server.</em></blockquote><p>Then we translate the requirements above into our own interpretation:</p><pre>// 1. if user is not in cache, remote is called (Req 1)</pre><pre>// 2. if fetch remote succeed, user from remote is returned (Req 2)<br>// 3. if fetch remote succeed, user is cached (Req 2)<br>// 4. if fetch remote fail, user is not cached (Req 2)</pre><pre>// 5. if user is in cache, remote is not called (Req 3)<br>// 6. if user is in cache, user from cache is returned (Req 3)</pre><p>Then, after that, we can start turning each of them into the test method, and just clear the comments afterward. This is a good habit because you will have an exhaustive list of things to test from the beginning, instead of losing track after writing a couple of test methods due to context switching.</p><h4>Comment and Give Clear Distinctions Between Given/When/Then (Arrange/Act/Assert)</h4><p>In general, unit test methods consist of 3 parts: conditioning, action, and verifying the result. This is often called Given-When-Then, or, I like this one better: Arrange-Act-Assert. Consider turning the first statement above (<em>if user is not in cache, remote is called</em>) into a test, then it will be like this:</p><pre>@Test<br>fun fetchUser_userNotInCache_remoteFetchIsCalled() {<br>    // Arrange<br>    `when`(cacheMock.getUser(ArgumentMatchers.anyString()))<br>            .thenReturn(null)<br>    `when`(endpointMock.fetchUser(ArgumentMatchers.anyString()))<br>        .thenReturn(EndpointResult(EndpointStatus.SUCCESS, USER_ID, USERNAME))<br><br>    // Act<br>    SUT.fetchUser(USER_ID)<br><br>    // Assert<br>    verify(endpointMock).fetchUser(USER_ID)<br>}</pre><p>Put labels for each section and spaces between them. It makes it much more readable.</p><p><strong>Extract the Code in “Arrange” Section into Separate Helper Methods</strong></p><p>Chances are, you are going to reuse the “arrange” part in other methods. For example, “<em>if the user is in cache</em>” is called in two test methods. So, extract them into separate methods. This also makes our unit test cleaner.</p><pre>// helper methods<br>fun userInCache() {<br>    `when`(cacheMock.getUser(ArgumentMatchers.anyString()))<br>        .thenAnswer <strong>{<br>            </strong>val userId = <strong>it</strong>.<em>arguments</em>[0] as String<br>            User(userId, USERNAME)<br>        <strong>}<br></strong>}</pre><pre>fun userNotInCache() {<br>    `when`(cacheMock.getUser(ArgumentMatchers.anyString()))<br>            .thenReturn(null)<br>}</pre><h4>Use Live Template</h4><p>Using Live Template, you can automatically generate comments for Arrange, Act, and Assert and give spaces between them. To do this, go to <strong>Preferences</strong> (Cmd+,) &gt; <strong>Editor</strong> &gt; <strong>Live Templates</strong> &gt; <strong>Add</strong> (Cmd+N) &gt; <strong>1. Live Template</strong>. Give “Abbreviation”, which in my case is “test”, because: (1) it’s short enough, and (2) it’s self-explanatory. And fill out some short description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_GfoqH1HU7KnUaRf2hflg.png" /></figure><p>Then put the template part:</p><pre>@org.junit.Test<br>fun $NAME$() {<br>    // Arrange<br><br><br>    // Act<br>    $END$<br><br><br>    // Assert<br><br>}</pre><p><em>$END$</em> is a special variable that specifies where your cursor is going to end up. I put this under the “Act” comment because this part will never be empty (while you <em>could</em> do the test without the “Arrange” part at all).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*M0P1CCyUn9h76AteuiLc1A.gif" /></figure><h4>Use whenever instead of `when`</h4><p>Now that we are using Mockito-Kotlin, there is this function, whenever() which is an alias for Mockito.when() (that we have to escape with backticks because when is a reserved word in Kotlin). Just prettier.</p><h4>Bonus: Use assertThat instead of assertEquals</h4><p>Because of this:</p><p><a href="https://stackoverflow.com/questions/1701113/why-should-i-use-hamcrest-matcher-and-assertthat-instead-of-traditional-assert">https://stackoverflow.com/questions/1701113/why-should-i-use-hamcrest-matcher-and-assertthat-instead-of-traditional-assert</a></p><p>By the way, I’d like to give credit to <a href="https://www.udemy.com/user/vasiliy-zukanov/">Vasiliy Zukanov</a> for a lot of what I wrote here. His “Android Unit Testing and Test Driven Development” course on Udemy is totally exemplary. That’s it for now. I hope you enjoyed the post :]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d70beff401" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ruangguru-engineering/tips-on-unit-testing-in-android-with-kotlin-d8d70beff401">Tips on Unit Testing In Android with Kotlin</a> was originally published in <a href="https://medium.com/ruangguru-engineering">Ruangguru Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveling Up The Software Engineer]]></title>
            <link>https://medium.com/ruangguru-engineering/leveling-up-the-software-engineer-99b752363bc4?source=rss----2c3b1fdf5d48---4</link>
            <guid isPermaLink="false">https://medium.com/p/99b752363bc4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[engineering-culture]]></category>
            <dc:creator><![CDATA[Harits Fahreza C.]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 08:35:11 GMT</pubDate>
            <atom:updated>2019-08-26T08:35:11.688Z</atom:updated>
            <content:encoded><![CDATA[<p>As the largest education startup in Indonesia, Ruangguru has a mission to build a world-class engineering team that would serve approximately 52 million students in Indonesia. With that challenge, we, as a Software Engineer in Ruangguru, cannot be ordinary with their day-to-day job is just coding based on their users request without any “special responsibility”. There are some initiatives that we approach in Ruangguru to level up the responsibility of our Software Engineers.</p><figure><img alt="Man holds a computer, sitting in a chair near the apartment windows" src="https://cdn-images-1.medium.com/max/1024/0*2_45rzOSNo2cBmWy" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Product Brainstorm</h3><p>The common problems in the software development lifecycle are the timeline that does not make sense with the scope of the product. To tackle that problem, we take part in the product or feature initiation that would be delivered. Together with our product team, we give continuous feedback to make sure the product can be delivered based on the preferred timeline. We also give our suggestion regarding the flow, business process, integration with the current product, and other business-related things from our perspective, to reduce the delivery time but still ensure the product quality. To make the product specification and the discussion result accessible, we use <a href="http://quip.com/">Quip</a> to create a document that makes all of the stakeholders can collaborate with ease.</p><h3>Design First</h3><p>To build a world-class software quality, we always put the design-first principle to our software development lifecycle. We start to mingle with our peers to get the whole context of the product that we would deliver. After that, we brainstorm the high-level architecture design, database structures, endpoint contracts, algorithm, and other things that necessary for the product. All of the Software Engineers can contribute directly, give some advice and opinion, instead of a System Analyst or Technical Lead that in charge of the software architecture design. From that initiative, it increases our sense of belonging to the software that we code. Another benefit from the Design-First principle is we will not need to create the documentation at the end of the lifecycle.</p><h3>Coding Time</h3><p>Of course, there is no Software Engineer without coding. But the real challenge is how we do coding with the easy collaboration with each other, keep our code quality high, and of course, makes the software engineers stay happy.</p><p>In Ruangguru, we implement the<strong> </strong><a href="https://martinfowler.com/articles/microservices.html"><strong>microservice architecture</strong></a><strong> </strong>to all of our product services. One of the problems that we encounter as our codebase grows is the lack of sense of belonging to the software engineers to the service that they do not work on it. At the end, when the problem come up in a service, we depend on the software engineer that works on it and makes the knowledge unscalable.</p><p>To tackle that problem we implement <a href="https://en.wikipedia.org/wiki/Monorepo"><strong>Monorepo</strong></a> in our version control system. So instead of creating multiple repositories for each of those services, we create a single big repository that contains all of our source code. We also<strong> create a shared library </strong>to reuse the common library to will use across the services e.g. Authentication Middleware, logging format, and error code dictionary.</p><p>We use the Merge Request feature to review the code that would be merged into our master codebase. We also maintain our unit tests on approximately 70% code coverage on average. This practice would keep our code quality high, although our codebase is getting bigger.</p><h3>Deployment</h3><p>With more than a hundred services that need to be deployed whenever the teams want, we cannot leave the deployment thing to our DevOps Engineers due to the limitation of the people. So, we create <strong>“Newton”, </strong>our internal service that handles service deployment-related things e.g. deployment to the Kubernetes, versioning, environment, and scaling configuration. To make it accessible to all of the Software Engineers, we create CLI (Command Line Interface) based tools called <strong>“rogu”</strong>. Using <strong>“rogu”</strong>, we can deploy our services, right from our local environment. With that internal platform, we can deploy the service to the environment what we need, maintain the versioning, and also the server scaling of the services.</p><h3>Monitoring</h3><p>The production environment is like a battlefield. We will not know what would happen there. Sometimes the database connection is broken or the service crash due to unexpected user input. Again, we cannot always depend on our DevOps Engineers to get the log, or to know what happens on the server. Because of that, we use <a href="https://www.solarwinds.com/papertrail">Papertrail</a> to pool all of our services log in a centralized place, use <a href="https://prometheus.io/">Prometheus</a> to monitor all of our services metrics like CPU and Memory Usage, and use <a href="https://grafana.com/">Grafana</a> to show the data that gathered in Prometheus beautifully. We also create some alerting on Papertrail and Prometheus, to notify us if some error happened or something odd happened regarding the server usage. With all of the tooling that we used, the Software Engineers would also responsible to monitor their service without the hassle.</p><h3>Takeaways</h3><p>The Software Engineers at Ruangguru are encouraged to join the product initiation talks from the earliest time and give a suggestion from their perspective to make the product requirements aligned with the preferred timeline. We always put the design-first principle to our software development lifecycle to make our software architecture designing skill better. While coding, we try to make easy collaboration, with keep our code quality high using code review, and of course to make the Software Engineer happy. We create our internal tools to make the deployment and the monitoring easily.</p><p>As a Software Engineer at Ruangguru, we will have the opportunities to learn as a Product Manager, System Analyst, DevOps Engineer, and of course, become the Leveled Up Software Engineer. It is a great opportunity for the people that love challenges and eager to learn new things every day. Sounds very like you? Apply now via <a href="https://career.ruangguru.com/technology">https://career.ruangguru.com/technology</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b752363bc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ruangguru-engineering/leveling-up-the-software-engineer-99b752363bc4">Leveling Up The Software Engineer</a> was originally published in <a href="https://medium.com/ruangguru-engineering">Ruangguru Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC and gRPC Reflection]]></title>
            <link>https://medium.com/ruangguru-engineering/grpc-and-grpc-reflection-8cc1e395adb3?source=rss----2c3b1fdf5d48---4</link>
            <guid isPermaLink="false">https://medium.com/p/8cc1e395adb3</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[grpc-reflection]]></category>
            <category><![CDATA[evan]]></category>
            <dc:creator><![CDATA[Asepnur iskandar]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 11:28:56 GMT</pubDate>
            <atom:updated>2019-03-18T11:28:55.988Z</atom:updated>
            <content:encoded><![CDATA[<h4>intro to gRPC development</h4><p>Today’s popular infrastructure is Microservices. as definition Microservice is Collection of micro services and encompass a function of business that could be built in different languages. they could communicate each other to exchange data or any other purposes.</p><p>example: there are 4 services which are product, payment, voucher, and user service. user service has ability to check token and used for services to verify user. then when client make a transaction, product will send data to payment. perhaps client has voucher code than payment will communicate to voucher service. they communicate and exchange data until transaction success. the architecture approximately like the following bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*3z8XcVZzCPCIk3LGmtryAg.png" /><figcaption>example of microservices architecture</figcaption></figure><p>The question is how they communicate each other? The API — software intermediary that allows 2 applications talk to each other. <em>what kind of API</em>? <em>REST</em>? yes, the popular one is REST. <em>how does it work</em>? from the case above then we need to build user client in product to call to user service, user client in payment, user client in voucher, payment client in product, client, client, client, and client on each service. how if we have thousand service? It will take a time for writing client although for example we put authentication as middleware of each service. further, what if there are changes in the main services that the client has implemented on other services? boom!!. in this article I come with another approach for how services communicate each others that is <strong>gRPC</strong>.</p><h4>What is gRPC?</h4><p>gRPC is open-source framework developed by google, it part of the Cloud Native Computation Foundation(CNCF) at high level it allows to define Request and Response for RPC (Remote Procedure Call) — client can directly call registered function to service. On top of it, gRPC is modern, fast, efficient, build over http2, support streaming, using protocol buffer which is language interoperability etc. let’s break down the definition in next section.</p><h4>gRPC vs REST</h4><p>What the different between gRPC and REST? the answer is a lot, but basically the different comes from protocol they use namely <strong>http/1x</strong> and <strong>http/2</strong>.</p><ul><li><strong>REST use http/1x and gRPC use http/2</strong></li></ul><p>REST use http/1x to transmit data, http/1 use one TCP connection for one request. if there are much request http will create TCP connection as much as request which mean it will affect latency. gRPC use http/2 to transmit data and http/2 can use one TCP connection for many request it will reduce latency for initiating TCP connection.</p><ul><li><strong>REST use data format JSON, XML, Plaintext, etc and gRPC use Binary</strong></li></ul><p>Google protobuf is a binary format that claim more compact than JSON. the following image show protobuf more efficient than JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*PQDFCIPwUs1k7VpK-dTDkg.png" /><figcaption>example protobuf vs Json</figcaption></figure><p>Protocol buffer need 37 bytes for It’s data and JSON need 133 bytes. based on research conducted by <a href="https://nilsmagnus.github.io/post/proto-json-sizes/">nismagnus</a>, protocol buffer has smaller size than gzipped JSON size. it mean using protocol buffer will reduce bandwidth cost.</p><ul><li><strong>Code generation</strong></li></ul><p>In first case in microservices, using REST we need to code client from scratch to call others services and the more service we have the more client we need to create. with gRPC we only need to define .proto file one time, and generate it using protocol buffer to specific language that we desired then to call specific function in a service then we could point to generated code from .proto file to initiate connection to server one time and simply call specific function.</p><p>what? we need to write client too to call other service? yes, but promise me, it’s not as much as use REST where we need to think about path API, create entity of response, unmarshal response to entity and many others. how if we need to change message request/response in .proto file? simply you can update message without change ordering of field of message. — <a href="https://developers.google.com/protocol-buffers/docs/proto3#reserved">more</a></p><h4>Role Protocol Buffer in gRPC</h4><p>In gRPC protocol buffer used to define message and service, then generate code from it. protocol buffer use extension .proto file to define probuf file. the following code is sample of protobuf file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/555f68c62a148687562909182f4f45d3/href">https://medium.com/media/555f68c62a148687562909182f4f45d3/href</a></iframe><p><em>message</em> annotation is to define object request and response payload, <em>service</em> to define service. inside of service is function definition that define name of function, payload request of function and response of function. other wise it can specify type of gRPC call like Unary, Client Streaming and etc. it will explain in other section. Why Protocol buffer? first, it easy to write message and service definition. The definition of the API is independent from implementation and huge amount of code can be generated to any language — officially gRPC support for 12 language but there are a lot of unofficial language like swift that can be generated from .proto file.</p><h4>4 Types of API in gRPC</h4><p>There are 4 types of API in gRPC that is Unary, Server Streaming, Client Streaming, and Bi-directional Streaming.</p><ul><li>Unary RPC</li></ul><p>Unary is simplest type of gRPC, where client send single request and server get back with single response. the following code is example of protocol buffer with type of unary RPC.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/285b6260e52bc16bb110b2b2a0576786/href">https://medium.com/media/285b6260e52bc16bb110b2b2a0576786/href</a></iframe><ul><li>Server Streaming RPC</li></ul><p>Server Streaming is client send single request to server and server get back a stream of responses after getting the client’s request. to define streaming to service, annotation stream is needed in protocol buffer file when define function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4415ea45db3c665e5f327a06dbbb889/href">https://medium.com/media/e4415ea45db3c665e5f327a06dbbb889/href</a></iframe><ul><li>Client Streaming</li></ul><p>Client Streaming is client send a stream of requests to the server instead of single request then server get back with single response. similar to server streaming RPC we need stream annotation to define streaming, but fo client streaming we put it in parameter request of function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4930e65382160ae7da715cc7acf1d7d0/href">https://medium.com/media/4930e65382160ae7da715cc7acf1d7d0/href</a></iframe><ul><li>Bi-directional Streaming</li></ul><p>Bi-directional Streaming is client send a stream of request to the server while client sending request, server could send a stream of responses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f69d79f70c25a992ce646b540f1ad8e5/href">https://medium.com/media/f69d79f70c25a992ce646b540f1ad8e5/href</a></iframe><p>process transmit data between client and server depend on context and logic of client and server. 4 types above could be describe like the following image bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*rdflKABGrhOfFdhyzeBUQw.png" /><figcaption>Flow Unary, Server Streaming, Client Streaming and Bi-Directional design</figcaption></figure><h4>gRPC Reflection</h4><p>as mentioned in previous section to call service we need to make connection to server as client. This is fine in production. what if for development when we need to check detail of service and event to call functions? one of bunch the answer is <strong>gRPC reflection. </strong>combined with <a href="https://github.com/ktr0731/evans"><strong>evans</strong></a> we could inspect manually gRPC API and event to automate task by scripting. it’s very simple to implement gRPC reflection with evans. first, you need to register <a href="https://github.com/grpc/grpc-go/tree/master/reflection"><strong>reflection</strong></a> in your server then install <a href="https://github.com/ktr0731/evans"><strong>evans</strong></a><strong> </strong>then simply call port gRPC service via evans<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*MTiI5UXPa5NJjskd_tKdxg.png" /><figcaption>using evans with CLI mode</figcaption></figure><h4><strong>Conclusion</strong></h4><p>gRPC is modern approach for internal service communication. the are a lot of benefit like easy to implement, save development cost, has benefit of http/2. support streaming multi direction, support interoperability language using protocol buffer, and has a lot of tools for development like gRPC reflection with evans.</p><h4>gRPC Deep Dive</h4><ol><li>gRPC Interceptor</li><li>gRPC with SSL</li><li>using deadline</li><li>combine REST with gRPC to migrate REST to gRPC little by little — gRPC Gateway.</li></ol><p>Thanks for read my article. support me with your claps if you like my article and don’t be hesitate to give me feedback or maybe you have an idea for next article, feel free to tell me in the comment down bellow 😃</p><h4>References</h4><ol><li><a href="https://microservices.io/">https://microservices.io/</a></li><li><a href="https://github.com/ktr0731/evans">https://github.com/ktr0731/evans</a></li><li><a href="https://tools.ietf.org/html/rfc7540">https://tools.ietf.org/html/rfc7540</a></li><li><a href="https://hpbn.co/http2/">https://hpbn.co/http2/</a></li><li><a href="https://nilsmagnus.github.io/post/proto-json-sizes/">https://nilsmagnus.github.io/post/proto-json-sizes/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cc1e395adb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ruangguru-engineering/grpc-and-grpc-reflection-8cc1e395adb3">gRPC and gRPC Reflection</a> was originally published in <a href="https://medium.com/ruangguru-engineering">Ruangguru Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>