<?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 Tamás Kozmér on Medium]]></title>
        <description><![CDATA[Stories by Tamás Kozmér on Medium]]></description>
        <link>https://medium.com/@kozmi?source=rss-4c2abd773e21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FS7BYPqMBARisjchRoz3fg.png</url>
            <title>Stories by Tamás Kozmér on Medium</title>
            <link>https://medium.com/@kozmi?source=rss-4c2abd773e21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:37:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kozmi/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[Flexible RecyclerView Adapter with MVVM and Data Binding]]></title>
            <link>https://proandroiddev.com/flexible-recyclerview-adapter-with-mvvm-and-data-binding-74f75caef66a?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f75caef66a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 14:10:16 GMT</pubDate>
            <atom:updated>2021-08-17T14:10:41.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*--oqCBmdxONAO8aSAD17oQ.png" /></figure><p>Three years ago I wrote an article about <a href="https://medium.com/android-news/how-to-bind-a-list-of-items-to-a-recyclerview-with-android-data-binding-1bd08b4796b4">binding a list of items to a RecyclerView</a> that became quite popular. It’s not really a surprise, since creating lists is one of the most common use cases in Android development.</p><p>A lot of things happened since then. Most importantly we got an official architecture guideline from Google with the Android Architecture Components. Also much more projects are using Data Binding nowadays.</p><p>I thought it’s time to revisit this topic and see how we can achieve something similar using the AAC ViewModel, but this time we will go a little further. We will create a RecyclerView Adapter that can be used to bind multiple types of data in the same list.</p><h3>Sample App</h3><p>To showcase how can we bind data with multiple view types, we will create the following sample app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*WQgWonHvAXE9ICmqAG-u2A.gif" /></figure><p>The list has three types of items: headers, car listings, and some promoted listings that stand out from the rest.</p><h3>ViewModel</h3><p>We start with implementing the ViewModel. This will be really simple in our case. We just get the data from our data provider asynchronously, do some transformations on the raw data to make it suitable for our UI, then set the value of our LiveData object which will be bound to the XML layout.</p><p><em>If you are not familiar with the AAC ViewModel I suggest reading about it first in the </em><a href="https://developer.android.com/topic/libraries/architecture/viewmodel"><em>official Google documentation</em></a><em>.</em></p><p>Note: I used Hilt for dependency injection and Coroutines for background processing in this sample project, but those are absolutely not necessary to understand and implement this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73799f991f409d2808c3802e20ed941f/href">https://medium.com/media/73799f991f409d2808c3802e20ed941f/href</a></iframe><p>The most important thing from the above code is the data property which will hold all the data what we need for our UI. This data will contain a list of ItemViewModel instances.</p><h3>ItemViewModel</h3><p>The ItemViewModel in the above code is an interface which represents the ViewModel part of the MVVM architecture on a list item level. These are not subclasses of the ViewModel class from AAC, but can also be observable (we will get back to this later).</p><p>You can see in the createViewData function that we add different objects (HeaderViewModel, CarAdViewModel, CarListingViewModel) to the list, depending on what we want to show on the UI. These are all implementations of the ItemViewModel interface, and represent the individual items in the list.</p><p>Let’s see how it looks like in code, it’s much easier to understand that way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0a3fc0bfc303d7f52c9debac91c29b8/href">https://medium.com/media/b0a3fc0bfc303d7f52c9debac91c29b8/href</a></iframe><p>All the ItemViewModel implementations will specify their layoutId what will be inflated when we need to show that item. They all have different properties that can be referenced in the layout files of the items to bind the data. For example here is the layout file of the HeaderViewModel to see how the properties are bound to the view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeb1dbb8a57277ec0e724d5fbcfe8c23/href">https://medium.com/media/aeb1dbb8a57277ec0e724d5fbcfe8c23/href</a></iframe><p>Finally we also need to define the viewType property for each ItemViewModel, because the RecyclerView need to know the view type of its elements. These can be simple constants.</p><h3>How It All Connects</h3><p>To connect the list of ItemViewModels in the CarListViewModel we will need to create two things. A custom RecyclerView.Adapter implementation and a <a href="https://developer.android.com/topic/libraries/data-binding/binding-adapters">Binding Adapter</a>. We only need to create these once, then we can reuse it for every screen, where we need to show a list of items.</p><h4>BindableRecyclerViewAdapter</h4><p>Let’s start with the RecyclerView.Adapter implementation, it’s the more complicated of the two, but we will go through all of the important callbacks step by step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9faa0cf663f89c465565ef8421995677/href">https://medium.com/media/9faa0cf663f89c465565ef8421995677/href</a></iframe><p>So the adapter has two properties:</p><ul><li>The itemViewModels represents the content of the list.</li><li>The viewTypeToLayoutId is a map that associates the possible view types of this adapter with the layout id of that specific view type. This is important, because when we create the ViewHolder we only know the view type, but we also need to know what layout to inflate for that ViewHolder.</li></ul><p>And the callbacks what we need to implement are the following:</p><ul><li>onCreateViewHolder - We use the DataBindingUtil here to inflate our layout, because we are using Data Binding in the items as well. We inflate the layout into a ViewDataBinding object and create the BindableViewHolder with it. Later we can set variables to this binding, but this method is only responsible for creating the ViewHolder. We use the viewTypeToLayoutId here to get the correct layout id.</li><li>onBindViewHolder - This is where we can set the variables for the binding, in this case only the itemViewModel itself.</li><li>getItemViewType - This is a very important part of the implementation. Here we can use the position parameter to get the item and associate its layout id with its view type.</li></ul><p>There is also the updateItems method, what we will call from the Binding Adapter. This will just update the items and call notifyDataSetChanged. If you want to implement a more sophisticated version with animations, you can use <a href="https://medium.com/@gabornovak/use-diffutil-for-out-of-the-box-animations-d932a28d6229">DiffUtil</a> and notify each item change separately.</p><h4>Binding Adapter</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72064a98408da4ab28005a42604b2cf3/href">https://medium.com/media/72064a98408da4ab28005a42604b2cf3/href</a></iframe><p>If you are familiar what are Binding Adapters, this looks really simple. If the RecyclerView doesn’t have an adapter yet, we create a new one and assign it to the RecyclerView. After that we call the updateItems method on the adapter with our data.</p><p>This is how it looks like in the XML of the MainActivity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2dabc414f1a860b07423a83f52c02f/href">https://medium.com/media/ea2dabc414f1a860b07423a83f52c02f/href</a></iframe><p>And finally the code of the MainActivity where we inflate the binding and set the viewModel property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cd23f9306de50611f59107ec2110f49/href">https://medium.com/media/0cd23f9306de50611f59107ec2110f49/href</a></iframe><p>That’s it. We created a flexible custom RecyclerView Adapter that can be used on any screen with list content and we don’t need to create RecyclerView Adapters and ViewHolders anymore.</p><p>And the best thing is that this makes our code easily testable, since all the logic regarding the content of the list will be in the ViewModel. If we have any complex logic in the items, they can be also tested separately.</p><h3>Bonus Improvements</h3><p>While this code works great, it’s simple and reusable, there is always room for improvement. In most cases we won’t need these, but if code becomes more complex we might benefit from it.</p><h4>Making an ItemViewModel observable</h4><p>We sometimes have items that can react to specific events and change their appearance. Let’s take the previous promoted car listing item with the red border for example.</p><p>When the user clicks the price of the car, we want to change the color of the border. If we wanted to achieve this with the current implementation, we would need to create a new itemViewModel at that position and update the list. This is far from ideal.</p><p>If we make the CarAdItemViewModel observable by subclassing it from the BaseObservable class we can change the borderColor property when the price is clicked, notify that the property is changed and the UI will update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d7a5a00aec4c28a2b02c2f986d6bd1/href">https://medium.com/media/c8d7a5a00aec4c28a2b02c2f986d6bd1/href</a></iframe><h4>Binding any property to the item layouts</h4><p>In the previous example we are only binding the itemViewModel property to the inflated layout in the BindableViewHolder. In this case we will access the itemViewModel in the XML.</p><p>If we want to make this more flexible by defining what properties we want to bind, we can modify our code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3595051b20b5c3f1ee7794f84d886d9/href">https://medium.com/media/f3595051b20b5c3f1ee7794f84d886d9/href</a></iframe><p>Thanks for reading my article. I hope you found it useful, and it can help you make your users happier.</p><p>If you liked it share it with fellow Android developers. If you have any questions or suggestions feel free to leave a comment.</p><p>The complete code of this sample project can be found in the following Github repository:</p><p><a href="https://github.com/kozmi55/felxible-recyclerview-databinding">GitHub - kozmi55/felxible-recyclerview-databinding</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f75caef66a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/flexible-recyclerview-adapter-with-mvvm-and-data-binding-74f75caef66a">Flexible RecyclerView Adapter with MVVM and Data Binding</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your Android Views accessible with only one line of code]]></title>
            <link>https://proandroiddev.com/make-your-android-views-accessible-with-only-one-line-of-code-79714ab6ca7f?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/79714ab6ca7f</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 08:13:28 GMT</pubDate>
            <atom:updated>2021-02-21T15:57:56.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yylD17sTn5p9xgf5NX4pKg.png" /></figure><p>If you care about your app’s accessibility you probably have already faced the following error message while running your UI tests:</p><pre>There was 1 accessibility error: View falls below the minimum recommended size for touch targets. Minimum touch target size is 48x48dp.</pre><p>Even if you are not running accessibility checks in tests you may want to comply to Google’s accessibility standards about the size of touch targets, which is defined in this guide:</p><p><a href="https://support.google.com/accessibility/android/answer/7101858?hl=en">Touch target size</a></p><p>There are multiple solutions to this problem, and the most obvious and easiest one is just to add some padding to the clickable element.</p><p>This works in most cases, but if you have a background or a border in your button this solution will compromise your design. There can be also many more exceptions where this is not ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uenwq125b_CD5Y8Zhz4K3w.png" /><figcaption>Example from Google’s Material guidelines. If you increase the height of the first button to 48dp, you will have a different design with much more spacing.</figcaption></figure><h4>TouchDelegate to the rescue</h4><p>Fortunately Google has a built in solution for this, and that is the TouchDelegate class. With the help of this you can specify the area of the parent view, where touches will be delegated to the given child view. This might be confusing at first, but let’s see some code and it will be crystal clear.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27b03a77f41789243caa61f036410117/href">https://medium.com/media/27b03a77f41789243caa61f036410117/href</a></iframe><p>The code is really simple.</p><ul><li>Get the hit area of the button.</li><li>Change it according to our requirements.</li><li>Apply the TouchDelegate to the parent View.</li></ul><p>This is really nice, but every time we face this problem we would need to write a lot of code. We can create an extension function to simplify our life.</p><h4>Creating an extension function</h4><p>We could create an extension function for the View class from the above code with 4 parameters, where we specify how many pixels we want to add to each side. That would be already a pretty neat solution, but why not go even further?</p><p>The following extension function makes the View’s touch target accessible, without the need of any manual calculations of how many pixels we need to add.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8ca0201bbad33171db68afbf39454e4/href">https://medium.com/media/c8ca0201bbad33171db68afbf39454e4/href</a></iframe><p>The code with the comments is pretty self explanatory. We just need to calculate the width and the height of the view and adjust the touch target if needed.</p><p>As I promised at the beginning, here is how you can make your Views accessible with one line of code:</p><pre>mySmallButton.accessibleTouchTarget()</pre><h4>Limitations and additional notes</h4><ul><li>If you want to expand the touch target of multiple Views in the same parent, this solution alone won’t work, because the call on the second View will overwrite the parent’s touch delegate in this line: parentView?.touchDelegate = TouchDelegate(delegateArea, this). A simple fix for this is wrapping each View in a FrameLayout, so that would get the delegate instead of the original parent.</li><li>To make sure this really works, the parent should have enough space next to the View you want to expand. If your View is in the top left corner of the parent without any padding, the touch target can’t expand in that direction.</li><li>Accessibility Scanner can detect and account for the use of TouchDelegate only when running on Android 10 and later.</li><li>You can also test this manually if you enable Pointer location in the Developer options. You can see exactly where you tapped with the help of this tool.</li><li>Another bonus to this approach if you have touch feedback animation on your View it won’t show outside of it, even if the touch area is expanded.</li></ul><p>Thanks for reading my article. I hope you found it useful, and it can help you make your users happier.</p><p>If you liked it share it with fellow Android developers. If you have any questions or suggestions leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79714ab6ca7f" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/make-your-android-views-accessible-with-only-one-line-of-code-79714ab6ca7f">Make your Android Views accessible with only one line of code</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</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 inject mock dependencies into Android components using Dagger AndroidInjector]]></title>
            <link>https://medium.com/android-news/how-to-inject-mock-dependencies-into-android-components-using-dagger-androidinjector-e274c8f6a9a6?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/e274c8f6a9a6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 11:51:14 GMT</pubDate>
            <atom:updated>2018-09-09T11:51:14.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_5aVVEC48XXdLOV0bhPPcw.png" /></figure><p>A couple of days ago I digged up my <a href="https://github.com/kozmi55/Kotlin-Android-Examples">old project</a> to try out the new Architecture Components on it, but first I wanted to refactor it a little, since it is more than one year old.</p><p>The first thing I did is to change the Dagger configuration to use the new <strong>AndroidInjector</strong>. This is a relatively new feature from the <strong>dagger-android</strong> library to remove even more boilerplate code. If you are not familiar with it, you can read about it on the <a href="https://google.github.io/dagger/android">official site</a>. You can also check this <a href="https://github.com/kozmi55/Kotlin-Android-Examples/commit/74b1a06562d51101bdeec7d534f8bb4877638faf">commit</a> in my repository, it’s pretty simple.</p><p>As I expected my UI tests failed to build after the changes. First let’s see how it looked like before, and what caused the problems.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4c2aef243a98e67079e239a10a36896/href">https://medium.com/media/c4c2aef243a98e67079e239a10a36896/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8fe7344cfebb004784183d19e87d3ae/href">https://medium.com/media/e8fe7344cfebb004784183d19e87d3ae/href</a></iframe><p>In the previous implementation I had a reference to the component in my Application class, so it was easy to substitute it with a test component by assigning the field in the test. I have previously written an article about this, you can check it out here:</p><p><a href="https://android.jlelse.eu/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-3-df4cf3838581">Complete example of testing MVP architecture with Kotlin and RxJava — Part 3</a></p><p>With the new implementation this is not possible, because we don’t have a reference to the component. The DaggerApplication superclass takes care of the injection instead of us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/248557d5c65a2d49bb6f28c8d33db02c/href">https://medium.com/media/248557d5c65a2d49bb6f28c8d33db02c/href</a></iframe><p>This is how the new implementation looks like. Much simpler, and less boilerplate, also less boilerplate in activities and fragments. But how can we test this?</p><h4>Creating a TestApplication class</h4><p>We can create a different Application class, that will be used for testing. In this case we won’t subclass the DaggerApplication class, instead we will do the injection in the setUp method of our test classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/000e14f8c48f1af392ae9a3e8f4df9e2/href">https://medium.com/media/000e14f8c48f1af392ae9a3e8f4df9e2/href</a></iframe><p>You can see one thing that is worth explaining in this snippet. We implement the HasSupportFragmentInjector interface. This is the interface among many others ( HasActivityInjector, HasServiceInjector , etc…) what is implemented by the DaggerApplication class to inject provided dependencies into Android components. Since we only inject dependencies into Fragments, we don’t need to implement the other interfaces.</p><p>To use our TestApplication in instrumented test we also need to create a custom test runner class and set it in our build.gradle file as the testInstrumentationRunner in the defaultConfig closure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3c1448eda97ae31090f1e112c2c90ca/href">https://medium.com/media/f3c1448eda97ae31090f1e112c2c90ca/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c6d39b4547b165ff53fb7b32eda0b9b/href">https://medium.com/media/3c6d39b4547b165ff53fb7b32eda0b9b/href</a></iframe><p>Now we have everything what we needed to inject mocked dependencies into our instrumentation tests. Let’s see how the UserListFragmentTest class looks like after the modification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73ecd051b3ddcf6aa150d688581dc58c/href">https://medium.com/media/73ecd051b3ddcf6aa150d688581dc58c/href</a></iframe><p>You can see that we are doing a pretty similar thing, than in the first version of the class. We are creating the component, but instead of assigning it to the component field in the original CustomApplication class, we use it to inject the dependencies into the TestApplication class.</p><h4>Removing code duplication</h4><p>There is still some room for improvement in this code. If we create many instrumentation tests, we will need to add the same piece of code to every test class. There must be a better way to do it.</p><p>We can create a TestInjector class, what will get the TestApplicationModule in its constructor and make the injection. We can use this class in our setUp methods instead of writing the same code over and over again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc89cec6c546926d5984009a91e4df4b/href">https://medium.com/media/dc89cec6c546926d5984009a91e4df4b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c99d690e1ab37816bd8084f75b52ee3/href">https://medium.com/media/9c99d690e1ab37816bd8084f75b52ee3/href</a></iframe><p>First I wanted to create a JUnit test rule, but the problem is that test rules are evaluated before the setUp method, and we need to initialize our mocks first.</p><h4>Making it even more flexible with default arguments</h4><p>What happens when we have many dependencies provided by our TestApplicationModule, but we only want to mock some of them?</p><p>We can create fake implementation of some dependencies and specify them as default arguments in the constructor of our TestApplicationModule class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf73acb2e06aa1e89e7164dc9d4508f7/href">https://medium.com/media/cf73acb2e06aa1e89e7164dc9d4508f7/href</a></iframe><p>In this case we have the flexibility to only mock the dependencies, what we need. As you saw in the previous example, we only needed to mock the UserRepository.</p><h4>Summary</h4><p>Android instrumentation testing can be problematic, when we are using the new Dagger AndroidInjector, but there are only a couple of steps, what we need to do to make mocking possible:</p><ul><li>Create a TestComponent and a TestModule, that will provide fake dependencies.</li><li>Create a TestApplication class, that implements the appropriate interfaces.</li><li>Create a custom test runner, that will run our tests by using our TestApplication class.</li></ul><p>Thanks for reading my article. If you want to check out the whole code, you can find it in the following Github repository.</p><p><a href="https://github.com/kozmi55/Kotlin-Android-Examples">kozmi55/Kotlin-Android-Examples</a></p><p>If you liked it share it with fellow Android developers or give it a clap or two.</p><p>If you have any questions or suggestions leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e274c8f6a9a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/how-to-inject-mock-dependencies-into-android-components-using-dagger-androidinjector-e274c8f6a9a6">How to inject mock dependencies into Android components using Dagger AndroidInjector</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</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 bind a list of items to a RecyclerView with Android Data Binding]]></title>
            <link>https://medium.com/android-news/how-to-bind-a-list-of-items-to-a-recyclerview-with-android-data-binding-1bd08b4796b4?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd08b4796b4</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 02:54:43 GMT</pubDate>
            <atom:updated>2018-08-06T02:54:43.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COdoK8Y9SQV8jy1pYJJChA.png" /></figure><p>When using MVVM architecture Android Data Binding is the best way to propagate changes to the UI. If you are completely new to Data Binding I suggest you catch up on the basics before reading this article.</p><p><a href="https://developer.android.com/topic/libraries/data-binding/">Data Binding Library | Android Developers</a></p><p>There are plenty of data types that we can bind to the properties of different widgets, however when it comes to binding a list of items to a RecyclerView things are not so straightforward. You can’t just do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/755fe7702c8f5a794c03da2413d01587/href">https://medium.com/media/755fe7702c8f5a794c03da2413d01587/href</a></iframe><p>There is no such XML property, that binds data to a RecyclerView. We need an Adapter, what will get the list of items from a data source. In this article I show you a simple method to bind data to a RecyclerView in XML.</p><h4>Let’s see the following scenario</h4><p>We have a list of data coming from a backend service, that is constantly changing. Our ViewModel class requests the data and gets the updates. When we get the update, we need to update the UI with the new data. Here is the implementation of our ViewModel class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a27c5efe5824d0cafa6cb5e4f8f3ae42/href">https://medium.com/media/a27c5efe5824d0cafa6cb5e4f8f3ae42/href</a></iframe><p>We are using BaseObservable from the Data Binding library just for the sake of simplicity, but the same thing can be implemented with the new ViewModel class from the Architecture Components. Also for the same reason we are not using a real backend service, we just generate a list of random numbers every second.</p><p>Our Activity also looks pretty simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed8c6fe8a753273bb46d3af8d5cf972c/href">https://medium.com/media/ed8c6fe8a753273bb46d3af8d5cf972c/href</a></iframe><p>Now we only need to update the data in the Adapter, when it changes. How can we do that? We have multiple options:</p><ul><li>We can pass the Adapter to the ViewModel. I don’t really like this approach, because a ViewModel class should know nothing about the Adapter.</li><li>We can add an OnPropertyChangedCallback to the viewModel inside the Activity. This is acceptable, but adds some boilerplate code to our Activity.</li><li>We can write a custom Binding Adapter and use Data Binding.</li></ul><h4>Writing a custom Binding Adapter</h4><p>With a custom Binding Adapter we can specify our own binding logic for an XML property. We will write a custom binding logic, that gets the adapter from the RecyclerView and sets the data for it.</p><p>First we need to add a setData method to our adapter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64e26535f1128c9099c27bd6dd191da8/href">https://medium.com/media/64e26535f1128c9099c27bd6dd191da8/href</a></iframe><p>Now we can write our BindingAdapter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78fcd5f45e6b35b2d45c97be4f718242/href">https://medium.com/media/78fcd5f45e6b35b2d45c97be4f718242/href</a></iframe><p>As you can see this is really simple, but has a slight problem. This method is not too generic, and if we will have other adapters in our app, we will have to add many if-else branches.</p><p>Let’s fix this by creating a generic interface, what all of our adapters will implement, that need to use Data Binding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56aceb42831c3939deaadf14291183bf/href">https://medium.com/media/56aceb42831c3939deaadf14291183bf/href</a></iframe><p>You might wonder why aren’t we using a List here with a type parameter. It can work too, but this gives us more flexibility. Sometimes we need another data structure to populate a RecyclerView.</p><p>And finally we change the implementation of the BindingAdapter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/956b7d8de051a0da826b344764fd8f18/href">https://medium.com/media/956b7d8de051a0da826b344764fd8f18/href</a></iframe><p>After adding these changes to our codebase we can easily bind any data to a RecyclerView using the data XML property from the app namespace and keep our ViewModel and Activity/Fragment classes much more cleaner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e108957a7760bb4dbfefda4832f2f2c6/href">https://medium.com/media/e108957a7760bb4dbfefda4832f2f2c6/href</a></iframe><p>This is how our UserAdapter looks like after the changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea331ab6fd19a717023d37c78019abf/href">https://medium.com/media/eea331ab6fd19a717023d37c78019abf/href</a></iframe><p>As you can see binding data to a RecyclerView is quite simple to achieve, and it can reduce some boilerplate code from your Activity/Fragment classes, and keep your ViewModel classes clean, and if you are already using Data Binding for other widgets on the screen it is good to remain consistent.</p><p>You can find the whole example project in this Github repository:</p><p><a href="https://github.com/kozmi55/Bindable-Adapter-Example">kozmi55/Bindable-Adapter-Example</a></p><p>Thanks for reading my article.</p><p>If you liked it share it with fellow Android developers or give it a clap or two.</p><p>If you have any questions or suggestions leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd08b4796b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/how-to-bind-a-list-of-items-to-a-recyclerview-with-android-data-binding-1bd08b4796b4">How to bind a list of items to a RecyclerView with Android Data Binding</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete example of testing MVP architecture with Kotlin and RxJava — Part 3]]></title>
            <link>https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-3-df4cf3838581?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/df4cf3838581</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Mon, 23 Oct 2017 06:01:00 GMT</pubDate>
            <atom:updated>2017-10-23T06:01:00.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete example of testing MVP architecture with Kotlin and RxJava — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbS56S4ywAgXoIoNl97Cuw.png" /></figure><p>This is the last part of my series about Android testing. If you missed the first 2 parts don’t worry, you can understand this even if you haven’t read them. If you want to check them out anyway, you can find the links below.</p><ul><li><a href="https://android.jlelse.eu/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-1-816e22e71ff4">Complete example of testing MVP architecture with Kotlin and RxJava — Part 1</a></li><li><a href="https://android.jlelse.eu/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-2-ca150c688ab1">Complete example of testing MVP architecture with Kotlin and RxJava — Part 2</a></li></ul><p>In this part you will learn how to create UI tests in Espresso with fake data, how to mock dependencies with Mockito-Kotlin, and how to mock final classes in Android instrumented tests.</p><h3>Writing Espresso tests with fake data</h3><p>If we want to write UI tests, which always produce the same results, the most important thing we need to do is to make our tests independent from any data coming from the network, or from our local database.</p><p>In other layers we can easily achieve this by mocking the dependencies of the tested classes (as you have seen in the first 2 parts). This is a little bit different in UI tests. In the previous examples our classes got their dependencies in their constructor, so we could easily pass mock objects to the constructor. Android components are instantiated by the system, and they usually get their dependencies through field injection.</p><p>There are multiple ways to create UI tests with fake data. First let’s see how can we substitute the UserRepository with FakeUserRepository<strong> </strong>in our tests.</p><h4>Implementing FakeUserRepository</h4><p>The FakeUserRepository is a simple class, what provides us fake data. It implements the UserRepository interface. This interface is also implemented by the DefaultUserRepository, what provides us the real data in the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b3340dfeb386907c26373e9056cb2e6/href">https://medium.com/media/4b3340dfeb386907c26373e9056cb2e6/href</a></iframe><p>I think this code doesn’t need much explanation. We create a Single that emits a list of fake users. Although it’s worth to mention this part of the code:</p><pre><strong>val </strong>users = (1..10L).<em>map</em></pre><p>We can use the map function to create a list from a <a href="https://kotlinlang.org/docs/reference/ranges.html">range</a>. This can be very useful in cases like this.</p><h4>Injecting FakeUserRepository into our test</h4><p>Now we have our fake implementation of the UserRepository, but how can we use it in our test? With Dagger we usually have an ApplicationComponent and an ApplicationModule to provide the app level dependencies. We initialize the component in our custom Application class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28679107dcce23772ad3706096544600/href">https://medium.com/media/28679107dcce23772ad3706096544600/href</a></iframe><p>Now we will create a FakeApplicationModule and a FakeApplicationComponent, what will provide us the FakeUserRepository. In our UI tests we will set the component field to a FakeApplicationComponent.</p><p>Let’s see this in an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160b3909cba6d217678288f591ca93ae/href">https://medium.com/media/160b3909cba6d217678288f591ca93ae/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62efea76a94773ddba08b012aebd2fe/href">https://medium.com/media/e62efea76a94773ddba08b012aebd2fe/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab955439e6e006f318773daaa6a4f0e2/href">https://medium.com/media/ab955439e6e006f318773daaa6a4f0e2/href</a></iframe><p>The first two snippets were already explained above. The interesting part here is the MainActivityTest class. Let’s see what happens here.</p><p>In the setUp method we get a reference for the instance of our CustomApplication class, create our FakeApplicationComponent and then start the MainActivity.</p><p>It is important to start our Activity after we set the component. This can be achieved by passing an other constructor parameter to the ActivityTestRule constructor. The third parameter here is a boolean, what determines if the test runner should start the Activity immediately.</p><h4>An example Espresso test</h4><p>Now we can start writing some tests. I don’t want to get into the details of how to write test cases in Espresso, there are tons of tutorials out there, but let’s see a simple example.</p><p>First we need to add dependencies to our build.gradle. If we are using RecyclerView, we also need to add the espresso-contrib dependency on top of the usual espresso-core.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46e781f9f3cd2b704eba39c2a8347b6/href">https://medium.com/media/d46e781f9f3cd2b704eba39c2a8347b6/href</a></iframe><p>And our test looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00444bd240f85b3e4eb07c71f4605938/href">https://medium.com/media/00444bd240f85b3e4eb07c71f4605938/href</a></iframe><p>What happens here?</p><p>First we find our RecyclerView then perform a click on it’s first (0 index) item with the help of RecyclerViewActions.</p><p>After we make an assertion, that a Snackbar is shown with the text User 1: 100 pts.</p><p>This is a pretty simple test case. You can find more example test cases in the projects Github repository. The code changes of this part can be found in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8152c2065af2e0871ba1175cadecb92b3fa8417f">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8152c2065af2e0871ba1175cadecb92b3fa8417f</a></p><h4>Mocking the UserRepository in UI tests</h4><p>What should we do if we want to test the following scenario?</p><ul><li>Load the first page of the data with success</li><li>Load the second page with an error</li><li>Verify if a Toast is shown on the screen, when we try to load the second page</li></ul><p>We can’t use our fake implementation here, because it always returns success with a list of users. We can hack the implementation, that for the second page it returns a Single, what emits an error, but this is just not good. If we add another test cases, we need to hack it again and again.</p><p>We can mock the behavior of the getUsers method. For this we need to make slight modifications in the FakeApplicationModule.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159aa8fbd4d6b40d3cd041c2670319e5/href">https://medium.com/media/159aa8fbd4d6b40d3cd041c2670319e5/href</a></iframe><p>Now we pass the UserRepository in the constructor, so in our test we can create a mock object, and build our component using that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/105dc4f9d46f0695d321a30a54dd486e/href">https://medium.com/media/105dc4f9d46f0695d321a30a54dd486e/href</a></iframe><p>This is our modified test class. We are using the <a href="https://github.com/nhaarman/mockito-kotlin">mockito-kotlin</a> library, what I have already mentioned in the first part to mock the UserRepository. We need to add the following dependencies to build.gradle to use it.</p><pre>androidTestImplementation <strong>&quot;com.nhaarman:mockito-kotlin-kt1.1:1.5.0&quot;<br></strong>androidTestImplementation <strong>&#39;com.linkedin.dexmaker:dexmaker-mockito:2.2.0&#39;</strong></pre><p>Now we can modify the behavior of the mock. I created two private utility methods for this, that can be reused in the test cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bed4a3e8dd531747c72f451c02fc8ed/href">https://medium.com/media/4bed4a3e8dd531747c72f451c02fc8ed/href</a></iframe><p>The other change we need to make is to launch the Activity in the test case, after setting up the mock object, instead of doing it in the setUp method.</p><p>With this change our previous test case looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868e27d54c6645522c3f17d6e6cc4ab7/href">https://medium.com/media/868e27d54c6645522c3f17d6e6cc4ab7/href</a></iframe><p>There are some more test cases in the GitHub repository, including error cases. Changes from this part can be seen in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/3889286528ad5a88035358894fda9e0be8c145aa">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/3889286528ad5a88035358894fda9e0be8c145aa</a></p><h3>Bonus: Mocking final classes in instrumented tests</h3><p>In Kotlin every class is final by default, which makes mocking complicated. In the first part we have seen how can we mock final classes with Mockito.</p><p>Unfortunatelly this method doesn’t work in Android instrumented tests. There are a couple of other solutions, what can be used in this case. One of them is the <a href="https://kotlinlang.org/docs/reference/compiler-plugins.html#how-to-use-all-open-plugin">Kotlin all-open plugin</a>.</p><p>This is a compiler plugin, that lets us create an annotation, what will make the class open if used on it.</p><p>To use it we need to add the following dependency to our top level build.gradle file:</p><pre>classpath <strong>&quot;org.jetbrains.kotlin:kotlin-allopen:</strong>$kotlin_version<strong>&quot;</strong></pre><p>And add these lines to our app modules build.gradle file:</p><pre>apply <strong>plugin</strong>: <strong>&#39;kotlin-allopen&#39;</strong></pre><pre>allOpen {<br>    annotation(<strong>&quot;com.myapp.OpenClass&quot;</strong>)<br>}</pre><p>Now we only need to create our annotation in the package we specified:</p><pre>@Target(AnnotationTarget.<strong>CLASS</strong>)<br><strong>annotation class </strong>OpenClass</pre><p>Example of the all-open plugin can be found in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8152c2065af2e0871ba1175cadecb92b3fa8417f">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8152c2065af2e0871ba1175cadecb92b3fa8417f</a></p><p>We reached the end of our long journey to cover every piece of code in our app with tests. Thanks for reading this far, I hope you found these articles useful.</p><p>If you liked it, hit the clap button or share it with fellow Android developers.</p><p>If you have any questions or suggestions leave a comment below or you can reach me on <a href="https://twitter.com/kozmi55">Twitter</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df4cf3838581" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-3-df4cf3838581">Complete example of testing MVP architecture with Kotlin and RxJava — Part 3</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete example of testing MVP architecture with Kotlin and RxJava — Part 2]]></title>
            <link>https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-2-ca150c688ab1?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca150c688ab1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Wed, 04 Oct 2017 09:07:59 GMT</pubDate>
            <atom:updated>2017-10-04T09:07:59.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete example of testing MVP architecture with Kotlin and RxJava — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UNbdQ1Dal4xg5caMSnmlw.png" /></figure><p>This is the second part of the article about testing every layer of an MVP app in Kotlin. In the first part we discussed the testing of the model layer and the interactor. If you missed it, you can check it out here.</p><p><a href="https://android.jlelse.eu/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-1-816e22e71ff4">Complete example of testing MVP architecture with Kotlin and RxJava — Part 1</a></p><p>In this part I will show you how to test the presenter by substituting the RxJava schedulers with test schedulers using the RxJavaPlugins and dependency injection. We will also see how to control the time of the schedulers in our tests.</p><h3>Testing the UserListPresenter</h3><p>The code of UserListPresenter is quite simple. It has only two public methods.</p><ul><li>getUsers — Requests the users from the interactor, and updates the UI according to the results.</li><li>onScrollChanged — Handles the scroll change of the RecyclerView. If we reach a specific element in the list, we already start to fetch the next page in the background, and show a loading indicator only, when the user reaches the last item, and the loading is still not finished.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab27ef1c2824c7766f7adfcaa6513c4/href">https://medium.com/media/fab27ef1c2824c7766f7adfcaa6513c4/href</a></iframe><p>The problem with testing this class is that we have dependencies on RxJava schedulers. We have multiple options to fix this.</p><h4>Overriding default RxJava schedulers with immediate scheduler</h4><p>First we will see how to substitute the RxJava schedulers with a scheduler, that instantly runs commands with the help of RxJavaPlugins.</p><p>RxJavaPlugins is a utility class, what allows us to modify the default behavior of RxJava. We only need it to change the default schedulers, but it can be used to change several other things about how RxJava works.</p><p>First let’s write a simple test for UserListPresenter and see what happens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8394ddc6e3254f36ffaf5814a524ac46/href">https://medium.com/media/8394ddc6e3254f36ffaf5814a524ac46/href</a></iframe><p>If you have read the first part, there should be nothing new here. We create some mock objects using Mockito, call some methods on the UserListPresenter, and then verify the expected behavior.</p><p>But if we try to run this test, we face the following error:</p><pre>java.lang.ExceptionInInitializerError<br>...<br>Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See <a href="http://g.co/androidstudio/not-mocked">http://g.co/androidstudio/not-mocked</a> for details.<br> at android.os.Looper.getMainLooper(Looper.java)</pre><p>This happens because the AndroidSchecdulers.mainThread() has dependencies from the Android framework, and we are creating a local unit test.</p><p>That’s where we can use the RxJavaPlugins and RxAndroidPlugins utility classes to override the default schedulers.</p><p>First we create an immediateScheduler field in our test class. We must extend the Scheduler class from RxJava and override the createWorker method to run the actions immediately. Then in the setUp method we call the static methods of the RxJavaPlugins and RxAndroidPlugins to override the schedulers. The below snippet shows the implementation of this. We also need to reset the schedulers in the tearDown method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4abbe3586a4a87f9b6a557480ad8862b/href">https://medium.com/media/4abbe3586a4a87f9b6a557480ad8862b/href</a></iframe><p>Now our test will pass. You can see that we overrode only two schedulers, but there are more in RxJava. Here we only use these two in the UserListPresenter, so it’s unnecessary to override the rest of them.</p><p>That’s great, but what if we have 10 presenters, and we need to do this in all of our tests? Fortunately we don’t have to do this. We can create a test rule, where we override the schedulers, and apply it in every test, where we need it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5adbe8fbc46e93c8121fc8e8a46eed4b/href">https://medium.com/media/5adbe8fbc46e93c8121fc8e8a46eed4b/href</a></iframe><p>In the test rule we override every scheduler, so if we use other schedulers, we can use the same test rule everywhere. If we never use a specific scheduler in our app, we can exclude it from the test rule as well.</p><p>To use our newly created test rule, we need to add the following code to our test class.</p><pre>@Rule @JvmField<br><strong>val immediateSchedulerRule </strong>= ImmediateSchedulerRule()</pre><p>We need to add the @JvmField annotation, because the @Rule annotation works only on fields and getter methods, but the immediateSchedulerRule is a property in Kotlin.</p><p>That’s it, now we can test our presenters using the immediate scheduler. The changes can be found in this commit (it also contains some test cases, what aren’t shown here):</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/c885758f47f58a5a818d8c9ff070190cc2a26e26">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/c885758f47f58a5a818d8c9ff070190cc2a26e26</a></p><h4>Using the TestScheduler to control the time</h4><p>The immediate scheduler is enough for most cases. But sometimes we need to control the time to test some functionality. Look at the onScrollChanged method in the UserListPresenter. How would you test it? The loading field will always be false, because the getUsers executes immediately. We can set the field public, but that would be bad practice to expose a field just because of testing.</p><p>RxJava has the TestScheduler class for these cases. This is a special scheduler, that allows us to manually advance a virtual time. Let’s see this in a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/208abf06e7989b369a7a0a4db87276b5/href">https://medium.com/media/208abf06e7989b369a7a0a4db87276b5/href</a></iframe><p>With the delay method we can create a Single, what doesn’t complete immediately. The third parameter of the method is a Scheduler. If we pass a TestScheduler instance, those 2 seconds will be virtual seconds. Now we can use the methods of the TestScheduler to manipulate this virtual time. This can be seen in row 18 of the example.</p><p>In our example, we have a Single, that takes 2 seconds to complete, and we advance the time only by 1 second. So when we scroll down, mockGetUsers.execute won’t get called one more time, because the first call is still loading, therefore we should verify, that the method will be called only once.</p><p>TestScheduler also have a advanceTimeTo method, what moves the time to a particular moment.</p><h4>Injecting the TestScheduler</h4><p>We could use the same way to replace the default schedulers with TestScheduler, what we used before, but for some reason it produced a strange error to me. When I ran the whole class of tests at once, only the first test passed, the rest of them always failed, because the actions were not triggered (I used TestScheduler.triggerAction method for simpler tests, where I didn’t need to control time). To solve this we need to use the advanceTimeBy method instead of triggerAction, even if we don’t need to control the time.</p><p>Although this solution works, this made me realize, that there is a much cleaner way to replace the schedulers, and it is <strong>dependency injection</strong>.</p><p>To do this first we create a SchedulerProvider interface, and two implementations of it.</p><ul><li>AppSchedulerProvider — This will provide us the real schedulers. We will inject this class to all of our presenters, and this will provide the schedulers for our Rx subscriptions.</li><li>TestSchedulerProvide — This class will provide us a TestScheduler instead of the real schedulers. When we instantiate our presenter in the test, we will use this as it’s constructor parameter.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/192b77a88c0e97dfeaa0498f04cd6218/href">https://medium.com/media/192b77a88c0e97dfeaa0498f04cd6218/href</a></iframe><p>Now we need to add the SchedulerProvider as a constructor parameter in the UserListPresenter and change the following lines</p><pre>.subscribeOn(Schedulers.io())<br>.observeOn(AndroidSchedulers.mainThread())</pre><p>to this:</p><pre>.subscribeOn(<strong>schedulerProvider</strong>.ioScheduler())<br>.observeOn(<strong>schedulerProvider</strong>.uiScheduler())</pre><p>We also need to add a provider method in our ApplicationModule, to provide the SchedulerProvider dependency.</p><pre>@Provides<br>@Singleton<br><strong>fun </strong>provideSchedulerProvider() : SchedulerProvider = AppSchedulerProvider()</pre><p>Now we can use the TestSchedulerProvider in our tests the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/258a427780cb5c4ba526dd9e33859990/href">https://medium.com/media/258a427780cb5c4ba526dd9e33859990/href</a></iframe><p>If we want to use the TestScheduler in the test, we get the property of the provider: testSchedulerProvider.testScheduler</p><p>That’s it. You can find more test cases, where we manipulate the time in the repository. I created some private utility methods to extract the common parts of these tests, and make the code cleaner. You can find it in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/eed5f3a938ac0fdc3a75ccfaede902c54810f56a">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/eed5f3a938ac0fdc3a75ccfaede902c54810f56a</a></p><p>Thanks for reading the second part of the series. We covered the topic of testing the presenters when using RxJava and learned different techniques for dealing with the RxJava schedulers in tests.</p><p>In the last part we will see how to make UI tests with fake data using Espresso and how to deal with some Kotlin specific problems in Espresso tests.</p><p>If you liked it, hit the clap button or share it with fellow Android developers.</p><p>If you have any questions or suggestions leave a comment below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca150c688ab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-2-ca150c688ab1">Complete example of testing MVP architecture with Kotlin and RxJava — Part 2</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete example of testing MVP architecture with Kotlin and RxJava — Part 1]]></title>
            <link>https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-1-816e22e71ff4?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/816e22e71ff4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Thu, 21 Sep 2017 06:32:26 GMT</pubDate>
            <atom:updated>2017-09-21T06:32:26.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete example of testing MVP architecture with Kotlin and RxJava — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*za1QozXO2Wo2GmrMpRLWXA.png" /></figure><p>Recently I created a <a href="https://github.com/kozmi55/Kotlin-Android-Examples">playground project </a>to learn more about Kotlin and RxJava. It’s a pretty simple project, but there was one part, where I had some struggle: testing.</p><p>Testing in Kotlin can have some pitfalls, and since it’s quite new, there are not so much examples out there. I thought it would be a good idea to share my experience to help you avoid my mistakes.</p><h4>About the architecture</h4><p>The app follows a basic MVP architecture with the repository pattern. It uses Dagger2 for dependency injection, and RxJava2 for data flow.</p><p>The repository provides the data from network or local storage, depending on different conditions. We use Retrofit for network calls, and Room for local database.</p><p>I won’t get into details about the architecture and these tools. I think most of you are already familiar with them. You can check out the starter project in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/ca29cad1973cd434ffb0b0d23c4465fc54e05c0b">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/ca29cad1973cd434ffb0b0d23c4465fc54e05c0b</a></p><p>We will start with testing the database and then go upwards in the layers.</p><h4>Testing the database</h4><p>For the database we are using <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room Persistence Library</a> from the Android Architecture Components. It is an abstraction layer over SQLite, that reduces boilerplate code.</p><p>This is the easiest part. We don’t need to do anything specific regarding Kotlin or RxJava. Let’s look at the code of the UserDao interface first, to decide what should we test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e88aec49a9080fdafc59498be2137a3/href">https://medium.com/media/8e88aec49a9080fdafc59498be2137a3/href</a></iframe><p>The getUsers function requests the next 30 users from the database depending on the page.</p><p>The insertAll inserts all the users in the list.</p><p>We can see a couple of things here, what needs to be tested:</p><ul><li>Check if the inserted users are the same as the retrieved users.</li><li>Check if the retrieved users are ordered correctly.</li><li>Check if we insert a user with the same id, it will replace the old record.</li><li>Check if we query a page, it will have a maximum of 30 users.</li><li>Check if we query the second page, we will get the correct number of elements.</li></ul><p>The below code snippet shows the implementation of the 5 cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5329c01985ab9595a7605d64aefbdb82/href">https://medium.com/media/5329c01985ab9595a7605d64aefbdb82/href</a></iframe><p>In the setup method we need to configure our database. We use Room’s in memory database to create a clear database before each test.</p><p>The tests are pretty simple here and don’t need further explanation. The basic pattern we follow in each test looks like this:</p><ol><li>Insert data to the database</li><li>Query data from the database</li><li>Make an assertion about the retrieved data</li></ol><p>We can use the functions from the Kotlin Collections API to simplify the creation of test data, like this part of the code:</p><pre><strong>val </strong>users = (1..40L).<em>map </em><strong>{ </strong>User(<strong>it</strong>, <strong>&quot;Name $it&quot;</strong>, <strong>it </strong>*100, <strong>&quot;url&quot;</strong>) <strong>}</strong></pre><p>We create a range, then map it to a list of users. There are multiple Kotlin concepts used here: ranges, higher order functions, string templates.</p><p>Commit: <a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8cebc897b642cc843920a107f5f0be15d13a925c">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/8cebc897b642cc843920a107f5f0be15d13a925c</a></p><h4>Testing the UserRepository</h4><p>For the repository and interactor we are going to use the same tools.</p><ul><li><strong>Mockito</strong> for mocking the dependencies of the classes.</li><li><strong>TestObserver</strong> for testing Observables (Singles in our case)</li></ul><p>But first we need to enable the option to mock final classes. In Kotlin every class is final by default. Fortunately Mockito 2 already supports mocking final classes, but we need to enable this.</p><p>We need to create a text file in the following location: test/resources/mockito-extensions/ with the name org.mockito.plugins.MockMaker and with the following text: mock-maker-inline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*8E7Hqy9GqdACWbfMGj4fnA.png" /><figcaption>Place of the file in Project view</figcaption></figure><p>Now we can start writing our tests using Mockito. First we add the dependency to the latest version of Mockito and JUnit.</p><pre>testImplementation <strong>&#39;org.mockito:mockito-core:2.8.47&#39;<br></strong>testImplementation <strong>&#39;junit:junit:4.12&#39;</strong></pre><p>The code of the UserRepository is shown in the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/485895a5b537bbcd98a16a34937a8858/href">https://medium.com/media/485895a5b537bbcd98a16a34937a8858/href</a></iframe><p>In the getUsers method we create a Single, what will emit the users or an error, if occurs. Depending on different conditions the shouldUpdate method decides, whether the users should be loaded from network or from local database.</p><p>One more thing to note is the CalendarWrapper field. It’s a simple wrapper with one method, what returns the current time. With the help of this we can mock the time in our tests.</p><p>So what should we test here? The most important thing to test here is the logic behind the shouldUpdate method. Let’s write some tests for it.</p><p>The way to test this is to call the getUsers method, and on the returned Single call the test method. The test method creates a TestObserver and subscribes it to the Single.</p><p>The <strong>TestObserver</strong> is a special type of Observer, that records events and allows making assertions about them.</p><p>We also have to mock the dependencies of the UserRepository, and stub some of their methods to return the data, what we specify. We can do this with Mockito the same way as in Java, or with the <a href="https://github.com/nhaarman/mockito-kotlin">Mockito-Kotlin</a> library by Niek Haarman. We will use Mockito in this example, but you can check the Github repository if you are curious.</p><p>If we want to use the when method from Mockito, we need to put it between backticks, because it is a reserved word in Kotlin. To make this look better, we can import the when method with a different name using the as keyword.</p><pre><strong>import </strong>org.mockito.Mockito.`when` <strong>as </strong>whenever</pre><p>Now we can use the whenever method for stubbing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8907d3a837c884e698c11e68677a6bbb/href">https://medium.com/media/8907d3a837c884e698c11e68677a6bbb/href</a></iframe><p>Above we can see the code of UserRepositoryTest. We are using Mockito annotations in this example to initialize the mocks, but it can be done in different ways. Every test consists of 3 steps:</p><ol><li>Specify what values should the stubbed methods return. We use the setUpStubbing private method to avoid boilerplate code in our tests. We can call this method in every test case with different parameters, depending on what state is under test. Kotlin’s default arguments can be really helpful here, because sometimes we don’t have to specify every parameter.</li><li>Call the getUsers method, and acquire a TestObserver by calling the test method on the returning Single.</li><li>Make some assertions on the TestObserver or on the mock objects to verify the expected behavior. In this example we use the assertNoErrors method, what verifies that the Single doesn’t emit an error. The other method we use is the assertValue. With the help of this we can make assertions about the value emitted by the Single. The way to do this is to pass a lambda to the assertValue method, which returns a boolean value. If it returns true, the assertion will pass. In this case we verify, that the emitted list contains 1 element. There are plenty of other methods to make assertions on the TestObserver, these can be found in the <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/observers/BaseTestConsumer.html">documentation of BaseTestConsumer</a>, what is the superclass of TestObserver.</li></ol><p>Changes can be found in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/17fc4645bb446879a0e44560c19d6c2c36810a89">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/17fc4645bb446879a0e44560c19d6c2c36810a89</a></p><h4>Testing the GetUsers interactor</h4><p>The method of testing the GetUsers interactor is similar to the one that we used to test the UserRepository.</p><p>GetUsers is a really simple class, it’s purpose is to transform the data coming from the data layer to data, what represents the users in the presentation layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddde7bce33d785346f0073080161ff8/href">https://medium.com/media/4ddde7bce33d785346f0073080161ff8/href</a></iframe><p>We use some transformations here from RxJava and also from Kotlin Collection API to achieve the desired results.</p><p>Let’s see how our tests look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a70ee62a59af6b1ef62b7448fb35ba/href">https://medium.com/media/72a70ee62a59af6b1ef62b7448fb35ba/href</a></iframe><p>The only difference here is that we are creating a fake Single object, what will be returned from the repository’s getUsers method. We are passing the UserListModel what should be emitted by the Single to the setUpStubbing method, where we create our fake Single, and set it as the return value of the repository’s getUsers method.</p><p>The rest of the code uses the same concepts, that we have seen in the UserRepositoryTest.</p><p>Commit after writing GetUsersTest:</p><p><a href="https://github.com/kozmi55/Kotlin-MVP-Testing/commit/49652a53813f004b2c11f962d8ba5666575365fc">https://github.com/kozmi55/Kotlin-MVP-Testing/commit/49652a53813f004b2c11f962d8ba5666575365fc</a></p><p>That’s all for the first part. We learned how to tackle some common problems while testing in Kotlin and using RxJava, how to utilize some Kotlin features to write simpler tests, and also took a look at testing the Room database.</p><p>In the second part I will show you how to test the Presenter with the help of TestScheduler, and how to make UI tests with fake data using Espresso. Stay tuned.</p><p>Thanks for reading my article.</p><p>If you liked it, hit the clap button or share it with fellow Android developers.</p><p>If you have any questions or suggestions leave a comment below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816e22e71ff4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-1-816e22e71ff4">Complete example of testing MVP architecture with Kotlin and RxJava — Part 1</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</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 make complex requests simple with RxJava in Kotlin]]></title>
            <link>https://medium.com/mindorks/how-to-make-complex-requests-simple-with-rxjava-in-kotlin-ccec004c5d10?source=rss-4c2abd773e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccec004c5d10</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Tamás Kozmér]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 11:18:25 GMT</pubDate>
            <atom:updated>2022-11-25T03:27:25.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TDsj6FQkEgAWGAFgjtGhwg.png" /></figure><p>It is a common problem in Android development when your API is not sending you exactly the same data, what you want to show in your views, so you need to implement more complex requests. Possibly your app needs to make multiple requests, that wait for each other, or call multiple requests after the previous one finished. Sometimes you even need to combine these two approaches. This can be challenging in plain Java and will often result in unreadable code, what is also painful to test.</p><p>Today I’m going to show you in a simple example how this can be achieved in a clean way using RxJava. The example is written in Kotlin, what makes the code more concise and easy to read. If you are completely new to RxJava or Kotlin, I suggest you catch up on the basics. There are some great resources here as well.</p><ul><li><a href="https://amitshekhar.me/blog/rxjava-tutorial">RxJava Tutorial</a></li><li><a href="https://amitshekhar.me/tags/kotlin">kotlin - Amit Shekhar | Mentor</a></li></ul><h3>Let’s see what do we want to achieve</h3><p>We will use the StackOverflow public API to request the details of a specific user, which consist of the users top 3 questions, top 3 accepted answers, and top 3 questions the user has favorited. The feature should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*0IPv58VtEmvDwxXg28YOMw.gif" /></figure><p>If we want to achieve this behavior, we need to the make 3 separate requests to the API. Since the requests doesn’t depend on each other, we will get the best results if we execute them in parallel and then combine their results. We also need to make one more request, because when we are requesting the answers, the response doesn’t contain the question belonging to that answer. In the following graph you can see how our requests will look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*ozkpBv8u8lik8uui2gVrSA.png" /></figure><p>To make it simpler, I won’t explain the code and the architecture of the whole app. We will only implement the <em>UserRepository</em> class, which provides the data for the presenter. You can find the complete source code in this <a href="https://github.com/kozmi55/Kotlin-Android-Examples/tree/complex_requests_with_rxjava_article">Github repository</a>, if you want to look at the rest of the code.</p><h3>Let’s do some coding</h3><p>We are going to implement the <em>getDetails</em> method in the <em>UserRepository</em>. This method provides the data for the <em>DetailPresenter</em> about the details of a user. Here is how it looks like at the beginning:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a612b0c82a3b16fa192d45020ba714/href">https://medium.com/media/a0a612b0c82a3b16fa192d45020ba714/href</a></iframe><p>You may wonder what is the <em>Single.create</em> method doing. It is just there so the app could be built successfully. It creates a <em>Single</em>, what emits an empty <em>DetailsModel</em>. We are using <em>Single</em> instead of <em>Observable</em>, because it’s better for our use-case.</p><p><em>Single</em> is similar to <em>Observable</em>,<em> </em>the difference is that it always emits exactly one value or an error. That is exactly what we need for a network call.</p><p>If you want to build the project and see what happens, or follow the example while coding it yourself you can check out this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-Examples/commit/388cc185ced48481964202aa63bad252f81c3c9d">https://github.com/kozmi55/Kotlin-Examples/commit/388cc185ced48481964202aa63bad252f81c3c9d</a></p><h4>Using the zip operator to combine the results of multiple requests</h4><p>First we implement the combination of the 3 requests. We will use the <em>zip</em><strong> </strong>operator from RxJava. The <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX documentation</a> says the following about the zip operator:</p><blockquote>Combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function</blockquote><p>So what does this mean exactly? It takes one item from each <em>Observable</em>, and applies a function to them, then emits the result. In our case it’s even simpler, because <em>Single</em> only emits one item, so we just specify a function to transform the individual items into one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4895334367ce6af07055bf6a4603705/href">https://medium.com/media/e4895334367ce6af07055bf6a4603705/href</a></iframe><p>This seems pretty simple, right? The <em>zip</em><strong> </strong>function’s first three arguments are the results of the Retrofit requests. The fourth one is a lambda expression, that has 3 parameters. Those have the same types as the responses. The thing we need to do in the lambda is to apply some operations on the parameters to create our <em>DetailsModel</em>.</p><h4>Using the Kotlin Collections API to create our DetailsModel</h4><p>I think one of the best things in Kotlin is its Collections API. It provides a lot of functions, that you can use to manipulate collections. Let’s look at some of them, while implementing the <em>createDetailsModel</em><strong> </strong>method:</p><ul><li><em>take</em>: This function is the most straightforward. It takes an <em>Int</em> parameter, and returns the first n elements of the collection. We use this, because we only want to show the first 3 items in each section.</li><li><em>filter</em>: As its name says, this function filters out specific items from the collection by a given predicate. Its only argument is a lambda, that receives the item and returns a <em>Boolean</em>. If it returns true, the item will be included in the collection. The lambda expression in the snippet is the same as this: <em>answer: Answer -&gt; answer.accepted</em>. If we only have one parameter in the lambda, we can omit its declaration, and use the <em>it</em> keyword instead.</li><li><em>map</em>: With the map function we can apply a transformation to a collection. In this example we transform the <em>Answer</em><strong> </strong>objects to <em>AnswerViewModel</em><strong> </strong>objects. The transformation is simple here, we just create <em>AnswerViewModel</em> with the right fields of <em>Answer</em>. The reason we need this is that the <em>Answer</em><strong> </strong>object we receive from the service doesn’t contain the title of the question, which the answer belongs to. Right now we just set it to “TODO” and deal with it soon.</li></ul><p>One final thing to note about this. When we are chaining these functions, we need to think about the order carefully. Let’s assume the first 3 answers we receive from the service are not accepted. If we change the <em>filter</em> and <em>take</em> functions, we won’t get any items in the end. Also if we change the <em>take</em> with <em>map</em>, the transformation will be applied to every element in the list, which is unnecessary.</p><p>The following commit contains the above changes:</p><p><a href="https://github.com/kozmi55/Kotlin-Examples/commit/61de3640a2ed2fd8f6c2605be78ba8a76e01fc37">https://github.com/kozmi55/Kotlin-Examples/commit/61de3640a2ed2fd8f6c2605be78ba8a76e01fc37</a></p><h4>Get the questions belonging to the answers</h4><p>If we want to show the titles of the questions belonging to the answers, we need to make an other request after we received the answers. This is usually done with the <em>flatMap</em> operator in RxJava. The <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/Single.html#flatMap(io.reactivex.functions.Function)">flatMap documentation for Single</a> states the following:</p><blockquote>Returns a Single that is based on applying a specified function to the item emitted by the source Single, where that function returns a SingleSource.</blockquote><p>Let’s simplify this with an example:</p><pre><strong>userService</strong>.getAnswersByUser(userId)<br>        .flatMap { answerListModel: AnswerListModel -&gt;<br>            <strong>questionService</strong>.getQuestionById(&quot;1234;2345;3456&quot;) }</pre><p>As you can see <em>flatMap</em> receives a lambda, which uses the emitted item as a parameter from the original <em>Single</em>. The return value of the lambda is a new <em>Single</em>, that can emit a different type of item, then the original one.</p><p>In the above example we are requesting specific questions by their id, but this is not enough. We need to get the question ids from the answers, then request the questions, and finally apply some transformations to the result to create a list of <em>AnswerViewModel</em> objects. The code snippet below shows how to achieve this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15f1aa8a760229fd546889aa009f6434/href">https://medium.com/media/15f1aa8a760229fd546889aa009f6434/href</a></iframe><p>Let’s focus on the <em>getAnswers</em><strong> </strong>method, and the other two methods it is using, the rest of the code is almost the same as before.</p><p>The <em>getAnswers</em> method looks similar to the <em>flatMap</em> example before, but in this case we are not making the request here, instead we call a method, where we construct and call our request. Here we use again the Collections API to transform the list of answers into a <em>String</em> of ids concatenated by the “;” character (This is the format StackOverflow needs).</p><p>The new thing here is the <em>joinToString </em>function. We can use this on any collection to make a single <em>String</em> from its elements.</p><p>After we have the ids, we are requesting the questions. This part of code might look confusing.</p><pre><strong>val </strong>questionsListModel = <strong>questionService</strong>.getQuestionById(ids)<br><br><strong>return </strong>questionsListModel<br>        .map { questionListModel: QuestionListModel? -&gt;<br>            addTitlesToAnswers(answers, questionListModel?.items ?: <em>emptyList</em>()) }</pre><p>Because of the <em>map</em> operator you might think <em>questionsListModel</em> is a collection, but it’s not. It’s a <em>Single</em>, like the result of every request in our example. There is also a <em>map</em> operator in RxJava, what works like the <em>map</em> in the Collections API. It can apply a transformation to the item emitted by the <em>Single</em>. So we are applying a transformation by calling the <em>addTitlesToAnswers</em> method.</p><p>The <em>addTitlesToAnswers</em> method is another good example of the power of the Collections API. We also use an other Kotlin concept here. Instead of declaring the lambda parameter as an <em>Answer</em> type we use destructing declaration. If you’re not familiar with it, you can read about it <a href="https://kotlinlang.org/docs/reference/multi-declarations.html">here</a>.</p><p>And now we have our <em>DetailsModel</em> constructed from multiple requests. You can check the full code in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-Examples/commit/1f5c587387eeebcebc65ab9b2ffc66190f5490ba">https://github.com/kozmi55/Kotlin-Examples/commit/1f5c587387eeebcebc65ab9b2ffc66190f5490ba</a></p><h4>There is always space for optimization</h4><p>If you look at the last snippet carefully, maybe you notice we made a mistake. It’s not critical, but it can slow down our request. We are requesting the questions for every answer, and in the end we just only take the first 3 answers. It would be better to only request those 3 questions. This little optimization made the request approximately 1 second faster on my phone. This change can be found in this commit:</p><p><a href="https://github.com/kozmi55/Kotlin-Examples/commit/1a6f0ef46d3e7edd1d816081dc1a6e7ab2de7d4a">https://github.com/kozmi55/Kotlin-Examples/commit/1a6f0ef46d3e7edd1d816081dc1a6e7ab2de7d4a</a></p><h3>Conclusion</h3><p>Although the learning curve for RxJava is steep, it is worth the time to learn the basics at least, especially the concepts that are useful in Android development. Some of these concepts are the things discussed above. Combining these with the Kotlin Collections API can really help you simplify your data flow, but if you are still using Java, this can be a great addition to your codebase too.</p><p>Thanks for reading my article. If you have any questions or suggestions, feel free to leave a comment. If you are interested in other Kotlin examples, you can check out the <a href="https://github.com/kozmi55/Kotlin-Android-Examples/tree/master">Github repository</a> of the project.</p><p><em>If you found this helpful, don’t forget to click the💚 below to make it reach more people.</em></p><h4>Recommended Reading</h4><p><a href="https://medium.com/mindorks/a-roadmap-to-become-a-better-android-developer-3038cf7f8c8d">A Roadmap To Become A Better Android Developer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccec004c5d10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/how-to-make-complex-requests-simple-with-rxjava-in-kotlin-ccec004c5d10">How to make complex requests simple with RxJava in Kotlin</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>