<?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[Weeronline - Medium]]></title>
        <description><![CDATA[Modern web and mobile development - Medium]]></description>
        <link>https://medium.com/weeronline?source=rss----fd4f2b5430d2---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Weeronline - Medium</title>
            <link>https://medium.com/weeronline?source=rss----fd4f2b5430d2---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 23:06:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/weeronline" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Our experience in migrating to coroutines from RxJava]]></title>
            <link>https://medium.com/weeronline/our-experience-in-migrating-to-coroutines-from-rxjava-143a6b5f3dcd?source=rss----fd4f2b5430d2---4</link>
            <guid isPermaLink="false">https://medium.com/p/143a6b5f3dcd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rxjava-android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Jasmine Villadarez]]></dc:creator>
            <pubDate>Wed, 05 May 2021 14:45:14 GMT</pubDate>
            <atom:updated>2021-05-05T14:45:14.351Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the challenges in developing Android applications is performing background tasks. As Android developers, we are given multiple choices — there are AsyncTasks, Services, Jobs, etc. Then there is RxJava — a library for composing asynchronous observable sequences.</p><p>For years, RxJava has been the holy grail for doing background tasks in Android. It made it easier to switch between threads and to propagate errors. It also prevented callback hell. However, most Android applications will only ever need to do API calls which means that most applications will not maximize RxJava’s full potential.</p><h4>Our RxJava usage</h4><p>Our usage of RxJava was simple. It was used for making sure API calls were running in the background thread and were not blocking the UI. There were no reactive streams usage. We call an API, wait for its response and display it on the screen.</p><h4>Why Switch?</h4><p>There are various advantages to using coroutines like having less method count, being relatively easier to grasp for junior developers and its Jetpack integration. Our major drive, however, is to have our data source or data module be Kotlin multiplatform ready. With Kotlin coroutines, we remove our dependency to RxJava which is only available for JVM platforms.</p><h3>Migration Process</h3><p>Our code base is relatively small. Still, switching from one library to another is not something you do in one go, especially with the way we integrated RxJava. Our usage of RxJava may be simple but all our API interfaces, unit tests and view models have Observables. We needed some way to make sure that we are able to rollout coroutines safely without worrying about things breaking in production.</p><p>That is where Flow comes in.Flow has a lot of extension functions that can make switching from RxJava painless. It enabled us to change just parts of our code to workable coroutines and have Flow bridge it to RxJava.</p><p>For instance, we have a PlaceRepository with a function getPlace that returns an Observable&lt;Place&gt;</p><pre>override fun getPlace(lat: Double, lon: Double): Observable&lt;Place&gt; {<br>    return <em>flow </em><strong>{<br>        </strong>val place = placeApi.getPlaceInfo(<br>                lat.<em>roundTo</em>(MAX_DECIMAL_PLACES),<br>                lon.<em>roundTo</em>(MAX_DECIMAL_PLACES)<br>        )<br>        emit(place)<br>    <strong>}</strong>.asObservable()<br>}</pre><p>As you can see from the sample above, the asObservable() extension function transforms Flow into an RxJavaObservable. getPlace invokers will be unaware that it is already using Flow .</p><p>Another approach is to immediately have Flow as the return type and call asObservable in the invoker code</p><pre>override fun getPlace(lat: Double, lon: Double): Flow&lt;Place&gt; {<br>    return <em>flow </em><strong>{<br>        </strong>val place = placeApi.getPlaceInfo(<br>                lat.<em>roundTo</em>(MAX_DECIMAL_PLACES),<br>                lon.<em>roundTo</em>(MAX_DECIMAL_PLACES)<br>        )<br>        emit(place)<br>    <strong>}</strong><br>}</pre><pre>private fun someCaller(lat: Double, lon: Double): Observable&lt;Place&gt;{<br>    return <em>placeRepository.getPlace(lat, lon).asObservable()</em><br>}</pre><p>This allowed us to already change snippets of code, rollout to production bit by bit and see if there are problems before completely switching out RxJava to Flow. High risks of breaking things in production were mitigated. Flow also has the advantage of having similar functions as RxJava which made adaptation relatively easy.</p><pre>fun getPlace(lat: Double, lon: Double) {<br>    viewModelScope.launch {<br>        placeRepository.getPlace(lat, lon)<br>            .flowOn(Dispatchers.IO)<br>            .collect {<br>                updatePlace()<br>            }.catch { emitError() }<br>    }<br>}</pre><h4>Suspending functions all the way</h4><p>Flow allowed us to remove RxJava dependencies smoothly. But the primary usage of Flow is still to return a sequence of results much like RxJava Observable. Our usage of Flowor Observable does not require a sequence of results — we make an API call and wait for its response. Thus, to be intentional in our code, we removed Flow and made our code simpler by using suspending functions.</p><pre>suspend fun getPlace(lat: Double, lon: Double): Place {<br>    return placeApi.getPlaceInfo(lat, lon)<br>}</pre><p>Caller:</p><pre>fun getPlace(lat: Double, lon: Double) {<br>    viewModelScope.launch(Dispatchers.IO) {<br>        val place = placeRepository.getPlace(lat, lon)<br>        updatePlace(place)<br>    }<br>}</pre><h3>Hurdles Encountered</h3><p>Migration from one technology to another always involves some challenges. It can be overwhelming especially with migrating from tightly-coupled codebases. In our migration, we encountered a few but the most notable ones are managing dispatchers and propagating errors.</p><h4>Switching Dispatchers and Unit testing with them</h4><p>In unit testing RxJava, there are functions to set all the schedulers to immediate. But, with coroutine dispatchers, this does not exist. Our solution for this is to create a DispatcherProvider class in which we override its implementation during testing. It’s not that much of a hassle but it is something to keep in mind.</p><h4>Propagating errors</h4><p>Perhaps one of the most challenging part for us in this migration is the propagation of errors. For RxJava, most errors can be caught and handled by onError function. Moreover, there is no need to worry about other jobs cancelling because of other jobs’ exception. It is a different story with using coroutines. There has to be awareness on where errors could occur and that those errors are properly handled to prevent cancellation of all jobs running in background.</p><p><a href="https://medium.com/androiddevelopers/exceptions-in-coroutines-ce8da1ec060c">Exceptions in coroutines</a> by Martin Vivo helped us in understanding how errors are passed from parent jobs to children jobs and vice versa.</p><p>Although this held us back a bit, we find that this caused us to be intentional in our code and be more aware of exceptions in our code.</p><h3>Conclusion</h3><p>Using RxJava, Flow or suspending functions still depends on how you use them. There is always more than one way to do things. Our code became more readable after migrating to coroutines and in my opinion, more accessible to junior Android developers because RxJava’s steep learning curve is out of the picture. We were also able to increase our crash-free rate because switching to coroutines increased our awareness of where exceptions can occur. Most importantly, our code is one step closer to being Kotlin multiplatform ready!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=143a6b5f3dcd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weeronline/our-experience-in-migrating-to-coroutines-from-rxjava-143a6b5f3dcd">Our experience in migrating to coroutines from RxJava</a> was originally published in <a href="https://medium.com/weeronline">Weeronline</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Transforms]]></title>
            <link>https://medium.com/weeronline/swift-transforms-5981398b437d?source=rss----fd4f2b5430d2---4</link>
            <guid isPermaLink="false">https://medium.com/p/5981398b437d</guid>
            <category><![CDATA[rotate]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[transformation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Eduardo Irías]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 12:31:01 GMT</pubDate>
            <atom:updated>2020-08-27T12:31:01.599Z</atom:updated>
            <content:encoded><![CDATA[<p>An affine transformation allows a UIView to be translated, scaled, rotated or skewed. UIViews have a CGAffineTransform property called <strong>transform</strong>.</p><p>What are affine transformations? Affine transforms are transformations that preserves proportions and collinearity between points.</p><h3>Transform Matrix</h3><p>The transform matrix of UIViews are represented by a 3 by 3 matrix. All the transformations are applied to the UIView’s bound center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*TPnPb9VOU2nLDlfbehkK4g.png" /><figcaption>Sample of a transform matrix</figcaption></figure><p>It’s possible to get and set a UIView’s transform property or matrix values.</p><pre>view.transform</pre><pre>view.transform.a</pre><h3>Identity matrix</h3><p>An identity matrix is a square matrix with ones placed diagonally and zero in all the other elements. This is the default value of the UIView’s transform property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*tm77FriqQoKV0Q6raB7WEQ.png" /><figcaption>Sample of an identity matrix</figcaption></figure><p>The identity matrix is useful to reset a view’s position, rotation or scale.</p><pre>view.transform = CGAffineTransform.identity</pre><p>Transform objects have a Boolean property <strong>isIdentity</strong>. It’s used to check if a view’s transform is the identity transform.</p><pre>view.transform.isIdentity</pre><h3>Translate Matrix</h3><p>To change a UIView’s position, a translate matrix is applied to the transform matrix. This will change the values <strong>tx</strong> and <strong>ty</strong> values of the transform matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*UmudYlBkBlKzZ0ct1CubSw.png" /></figure><p>CGAffineTransform’s have a function <a href="https://developer.apple.com/documentation/coregraphics/cgcontext/1455286-translateby"><strong>translateBy(x:y:)</strong></a><strong> </strong>and an initializer <strong>CGAffineTransform(translationX: , y: )</strong></p><pre>view.transform = view.transform.translatedBy(x: 100, y: 100)<br>view.transform = CGAffineTransform(translationX: 100, y: 100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*fHL3hDSvkwVl_aW030cnyg.gif" /><figcaption>Translate example</figcaption></figure><p>This function creates an affine transform matrix translating the current transform with the provided values.</p><p>It’s also possible to individually manipulate <strong>tx</strong> and <strong>ty</strong> values of the transform matrix.</p><pre>view.transform.tx = 100<br>view.transform.ty = 100</pre><h3>Scale Matrix</h3><p>A scale matrix is used to scale a UIView’s width and height. To change the scaling of a UIView a scaling matrix is applied to the transform matrix. The scale matrix changes the <strong>a</strong> and <strong>d</strong> values of the transform, where a is the xScale and <strong>d</strong> the yScale. The default values of <strong>a</strong> and <strong>d</strong> are 1 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*NL6PsVtqIIBFyAYZ2w_JAQ.png" /></figure><p>To scale a view, it’s possible to use the function, <strong>scaleBy(x:y:) </strong>and an initializer <strong>CGAffineTransform(scaleX: , y: )</strong></p><pre>view.transform = view.transform.scaledBy(x: 2, y: 2)<br>view.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)</pre><p>Scaling by both axis by 2, will double the image size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*IQMgRKzDAcdZZ_AOqFpDFQ.gif" /><figcaption>Scale example</figcaption></figure><p>It’s also possible to individually manipulate <strong>a</strong> and <strong>d</strong> values of the transform matrix.</p><pre>view.transform.a = 4.0<br>view.transform.d = 3.0</pre><h3>Rotation Matrix</h3><p>To rotate a UIView a rotation matrix is applied to the transform matrix. The rotation matrix affects the <strong>a, b, c </strong>and<strong> d</strong> properties of the transform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*IR0ZOpgvLksl-p-eh7JNKQ.png" /></figure><p>To rotate a view it’s possible to use the function, <strong>rotated(by:)</strong> and an initializer <strong>CGAffineTransform(rotationAngle: )</strong></p><pre>view.transform = view.transform.rotated(by: CGFloat.pi)<br>view.transform = CGAffineTransform(rotationAngle: angle)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*vB7NxhjOOzE-km8fULxPZQ.gif" /><figcaption>Rotation example</figcaption></figure><p>It’s possible to rotate a view, by setting the <strong>abcd</strong> values of the matrix.</p><pre>let angle: CGFloat = 45.0 * CGFloat.pi / 180.0</pre><pre>view.transform.a = cos(angle)</pre><pre>view.transform.b = sin(angle)</pre><pre>view.transform.c = -sin(angle)</pre><pre>view.transform.d = cos(angle)</pre><h3><strong>Skew</strong></h3><p>Skewing a view is possible by modifying the b and c values of the matrix.</p><pre>let angle: CGFloat = 45.0 * CGFloat.pi / 180.0</pre><pre>view.transform.b = cos(angle)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Z7kkH5dA0PmgPHpyIsMgWg.gif" /><figcaption>Skew in B</figcaption></figure><pre>let angle: CGFloat = 45.0 * CGFloat.pi / 180.0</pre><pre>view.transform.c = cos(angle)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*PeNwtwPwA6QmmJoeTZvFHQ.gif" /><figcaption>Skew in C</figcaption></figure><h3>Concatenation</h3><p>Performing multiple transformations to a UIView, might have unexpected outcomes.</p><pre>let angle: CGFloat = 45.0 * CGFloat.pi / 180.0</pre><pre>view.transform = CGAffineTransform(rotationAngle: angle)</pre><pre>view.transform = CGAffineTransform(translationX: 10.0, y: 0.0)</pre><pre>view.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)</pre><p>This code seems to rotate a view, translate it and later scale it. The final outcome of this algorithm is just a scaled UIView. This is because the transform is always reassigned, thus it’s removing the value of the previous matrix.</p><p>To assign multiple transformations on a view, it’s necessary to concatenate the transformation matrixes. The CGAffineTransform has a method:</p><p><strong>func concatenating(_ t2: CGAffineTransform) -&gt; CGAffineTransform</strong></p><p>The concatenating function receives <strong>t2 </strong>as parameter. It multiplies the current transform with <strong>t2</strong> and return the result of multiplication matrix.</p><pre><strong>let</strong> rotationMatrix = CGAffineTransform(rotationAngle: angle)</pre><pre><strong>let</strong> translationMatrix = CGAffineTransform(translationX: 10.0, y: 0.0)</pre><pre>view.transform = rotationMatrix.concatenating(translationMatrix)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*WO39k9_fTz56fS06oL5G4w.gif" /></figure><p>It’s important to remember some properties of matrix multiplications.</p><p>a.b != b.a</p><pre><strong>let</strong> rotationMatrix = CGAffineTransform(rotationAngle: angle)</pre><pre><strong>let</strong> translationMatrix = CGAffineTransform(translationX: 10.0, y: 0.0)</pre><pre>view.transform = translationMatrix.concatenating(rotationMatrix)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*_r0Dppeknt8XzoI16nqiCw.gif" /></figure><p>This code first translates the view and then rotates it. The rotation is calculated based on the UIView’s center. That’s the reason why the position seems to be off. The order of products is important when multiplying matrixes.</p><h3><strong>Conclusion</strong></h3><p>(/^▽^)/</p><p>It’s easier to perform translations, scaling or rotations to views using transforms in Swift. All the UIView objects have a transform property. It’s also possible calculate the matrix values and assign the resulting matrix to a UIView’s transform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5981398b437d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weeronline/swift-transforms-5981398b437d">Swift Transforms</a> was originally published in <a href="https://medium.com/weeronline">Weeronline</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our approach to modularization and MVVM]]></title>
            <link>https://medium.com/weeronline/our-approach-to-modularization-and-mvvm-44aae0a3ea41?source=rss----fd4f2b5430d2---4</link>
            <guid isPermaLink="false">https://medium.com/p/44aae0a3ea41</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jasmine Villadarez]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 15:00:26 GMT</pubDate>
            <atom:updated>2019-07-01T08:28:00.060Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past, maintainability of Android applications was quite a headache because activities, fragments and views were tightly coupled with one another. To remedy the situation, the Android development community introduced the idea of using MVP (Model-View-Presenter) pattern to lessen code coupling. In 2017, Google <em>softly pushed</em> for<em> </em>the usage of MVVM(Model-View-ViewModel) pattern with the announcement of <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">architecture components’ ViewModel</a>, the primary purpose of which was to help manage Android’s lifecycle better. More improvements in the Android architecture followed with the release of the <a href="https://developer.android.com/topic/libraries/architecture">Architecture Components</a> which were aimed at aiding developers in creating scalable, maintainable and testable applications.</p><p>With this article, we would like to share our journey in implementing a modularized application to help us scale, maintain and test our app with much more ease. We will discuss our architecture, why we decided to apply modularisation, how we modularized our app, what MV* pattern we used and what we learned from all of it.</p><h3><strong>Our architecture</strong></h3><p>In 2017, we were faced with the problem that our code was no longer maintainable; the codebase featured an improperly implemented MVP pattern, was hard to scale and potential side effects of the changes applied to the codebase were not immediately apparent. We had a big serving of spaghetti and we were not enjoying it!</p><p>The following year, we were given the opportunity to rewrite our app from scratch. We brainstormed on possible architectures wherein we could have have <em>clear separation of concern </em>to enable us to scale efficiently and have <em>testable code </em>to ensure its quality. Eventually, we came up with an architecture inspired by Uncle Bob’s <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfCrWhJTEzxaFnTzduOKBQ.png" /></figure><p>From the figure above, it is apparent that it is a simple architecture wherein there is a clear separation for API calls and local database related logic (data layer) from UI related logic (presentation layer). With this architecture, we would only need to expose repository interfaces to the presentation layer; the presentation layer would be unaware if the data comes either from an API or a local database. Thus, it would be possible to easily switch data sources without having any impact on the presentation layer.</p><p>Additionally, it would be easier for us to add unit tests for both layers because we would only need to test the <em>concern </em>of each layer. For the data layer, it would be verifying if the repository is parsing the data properly into the entities or if the local database is adding/removing/updating items correctly. And for the presentation layer, we would only check if each view model emits the correct state after performing an action.</p><p>It became obvious to us that with this approach, we could separate the app into two layers or modules. But why modularize when it is also possible to separate them by package? In our case, we had two reasons:</p><ol><li>We knew we were going to be using Kotlin to develop the new app and we wanted to take advantage of Kotlin’s language feature. With Kotlin’s internal visibility modifier, we can make a class/function/variable only available for a module which in turn helps us have <strong>additional safeguard</strong> for having separation of concern.</li><li>We wanted to have the flexibility to be able to use the data layer for another app easily without having to worry about it being coupled with the UI or presentation layer.</li></ol><h3><strong>Our modularization implementation</strong></h3><p>As explained above, we separated our app into two modules — data and app modules.</p><ul><li>Data module — contains all API calls and follows the standard repository pattern. The repository interfaces are the only one exposed and it does not expose its implementation classes.</li><li>App module — contains all UI related code. It has all the activities, fragments and custom views needed for each screen of the application and also has the widget provider for the app widget. This module <strong>depends on</strong> the data module.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyM0Ck4JOs4DA2NssZOrbA.png" /><figcaption>How our Android project looks like</figcaption></figure><p>We made the choice not to have separate modules for each feature of the app because our app consists only of small sized features, thus, it would not be very practical. Although for medium to enterprise size applications, it would be wise to separate the presentation layer into different feature modules. This is advantageous for larger teams that want to work simultaneously in different modules without impacting the other. Again, this emphasizes <em>separation of concern.</em></p><blockquote>How to provide the repositories to the app module without exposing their implementation classes?</blockquote><p>After we decided that we were going to modularize our app, we faced a new challenge — how to provide the repositories to the app module without exposing their implementation classes? Our answer was <a href="https://github.com/google/dagger">Dagger2</a>, a dependency injector library for Android and Java.</p><p>We created a dagger component inside the data module called <em>DataComponent </em>which provided all the <em>repositories </em>that the presentation layer might need.</p><pre>@Component<br>interface DataComponent {<br>   fun providesSampleRepository() : SampleRepository<br>   ...<br>}</pre><p>For the presentation layer to be able to use this, we created a dagger component called <em>AppComponent </em>and added the <em>DataComponent</em> as its dependency. This provided the <em>AppComponent</em> access to the repositories from the <em>DataComponent.</em></p><pre>@Component(dependencies = [<br>    DataComponent::class<br>])<br>internal interface AppComponent {...}</pre><p>Another thing to note is that the repositories in the <em>DataComponent</em> are scoped to only have one instance. This ensures that when the repository is already declared, it would not create another instance which in turn reduces memory usage.</p><h4><strong>Our MV* pattern</strong></h4><p>In the old version of the Weeronline app, MVP (model-view-presenter) was the pattern used to extract the business logic from activities and fragments. Interfaces were created for both the view and presenter to override so they would not communicate “directly” with each other.</p><p>It was a useful approach to lessen the load for activities and fragment, however, the presenter was still aware of the view thru its interfaces meaning we still had a reference of the View inside the Presenter. As much as possible, we wanted to avoid this because it might have caused memory leaks if a process in the Presenter was not stopped when the View was destroyed.</p><p>For the new app, we still wanted the advantages that MVP pattern gave us but with two additional benefits:</p><ul><li>something that would ensure that we do not have a reference to the view, making the <em>business logic handler</em> unaware of the existence of the view</li><li>something that can help us ensure we stop background tasks on process death</li></ul><p>Thus, it was a no brainer that we chose <strong>MVVM (model-view-viewmodel) pattern</strong>.</p><p><strong>How we implemented MVVM?</strong></p><p>There are different ways to implement MVVM, some with data binding and some without, but one thing that remains constant in its concept is that the ViewModel is unaware of the View and the View listens for emissions from the ViewModel.</p><p>In order to implement the MVVM pattern in our app, we used <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">architecture components’ ViewModel</a> and <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> and Kotlin’s sealed classes. We did not use <a href="https://developer.android.com/topic/libraries/data-binding">Android’s data binding library</a> as we found it unnecessary for our needs.</p><p>To demonstrate, I will provide an example using our search screen. It allows the user to search for a place, display a list of results when it finds a match and display a message if it did not find a result based on the provided text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOG3o1qQHPdtP-FlnK7vNg.png" /></figure><p><strong>State (Model)</strong></p><p>The State is the one we treat as the Model in the MVVM pattern. It contains valuable information for the View to render. Using Kotlin’s sealed classes, we define search screen’s possible states — InitState, SearchingState, NoResultState, and SearchResultState.</p><pre>internal sealed class SearchState {<br>    <em>/**<br>     * Initial state of search<br>     */<br>    </em>object InitState : SearchState()<br>    <br>    <em>/**<br>     * State when search is ongoing (fetching from API)<br>     */<br>    </em>object SearchingState : SearchState()<br><br>    <em>/**<br>     * State when there are no results found from the search string provided<br>     *<br>     * </em><strong><em>@param </em></strong><em>searchString - string used to search<br>     */<br>    </em>data class NoResultState(val searchString: String) : SearchState()<br><br>    <em>/**<br>     * State with search results<br>     *<br>     * </em><strong><em>@param </em></strong><em>searchedPlaces - list of places returned for a given search<br>     */<br>    </em>data class SearchResultState(val searchedPlaces: List&lt;Place&gt;) : SearchState()<br>}</pre><p><strong>ViewModel</strong></p><p>The ViewModel contains the logic to search for a place based on a query. It holds the State with <em>LiveData</em> to emit it to the View.</p><pre>internal class SearchViewModel : ViewModel() {<br>    private val _searchState = MutableLiveData&lt;SearchState&gt;()<br>    val searchState: LiveData&lt;SearchState&gt; = _searchState<br>    <br>    fun searchPlaces(searchString: String?) {<br>        searchString?.<em>takeIf </em><strong>{ it</strong>.<em>trim</em>().length &gt;= SEARCH_MIN_INPUT_CHARS <strong>}</strong>?.<em>let </em><strong>{<br>            </strong>Observable.timer(<br>                    SEARCH_THROTTLE_INTERVAL,<br>                    TimeUnit.MILLISECONDS<br>            ).flatMap <strong>{<br>                </strong>placeRepository.search(searchString)<br>            <strong>}</strong>.doOnSubscribe <strong>{<br>                </strong>_searchState.postValue(SearchState.SearchingState)<br>            <strong>}</strong>.subscribe(<strong>{<br>                </strong>if (<strong>it</strong>.<em>isEmpty</em>()) _searchState.postValue(SearchState.NoResultState(searchString))<br>                else _searchState.postValue(SearchState.SearchResultState(it))<br>            <strong>}</strong>, <strong>{<br>                </strong>_searchState.postValue(SearchState.NoResultState(searchString))<br>            <strong>}</strong>)<br>            return<br>        <strong>} </strong>?: _searchState.postValue(SearchState.InitState)<br>    }<br>}</pre><p><strong>View</strong></p><p>The View is dumb and listens only for the State that the ViewModel provides in order to render the user interface. From the code below, we have an instance of the ViewModel and in onCreate we listen for State emissions.</p><pre>internal class SearchActivity : BaseActivity() {<br><br>    @Inject<br>    lateinit var viewModelFactory: ViewModelProvider.Factory<br><br>    private val searchViewModel: SearchViewModel by <em>lazy </em><strong>{<br>        </strong>ViewModelProviders.of(this, viewModelFactory)[SearchViewModel::class.<em>java</em>]<br>    <strong>}<br><br><br>    </strong>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        searchViewModel.searchState.observe(this, <br>           <em>Observer </em>{ state -&gt;<strong><br>             </strong>renderSearchState(<strong>state</strong>)<br>        <strong>}</strong>)<br>    }<br><br>    private fun renderSearchState(searchState: SearchState?) {<br>        if (searchState == null) return<br>        when (searchState) {<br>            is SearchState.InitState -&gt; renderInitState()<br>            is SearchState.SearchingState -&gt; renderSearchingState()<br>            is SearchState.NoResultState -&gt; {<br>                renderNoResultState(searchState.searchString)             <br>            }<br>            is SearchState.SearchResultState -&gt; {<br>                renderSearchResultState(searchState.searchedPlaces)<br>            }<br>        }<br>    }</pre><p>Using the same technique for all screens, we were able to easily pinpoint bugs as there is now a clear separation of responsibility between the business logic and rendering of the view.</p><h3><strong>Learnings</strong></h3><p>Diving into unknown territory is always an adventure and a risk. In implementing our new architecture, we have improved our codebase considerably, however it was not without its challenges. There are two major learnings we would like to share:</p><ul><li>having the data module expose only its interfaces and necessary classes helped us when nearly at the end of development we needed to change our source of forecast data. Since the app module only knows about the interfaces and data models, we were able to switch easily into a new data source without changing the app module.</li><li>setting up the dependency graph was a bit tricky with a multi-module project. We wanted the modules to expose only what was necessary — such as the repository interfaces — and we chose to use Dagger for this. We can still improve by creating our own simple dependency injection solution so that our data module would not need to depend on Dagger. This might also give us the flexibility to change the dagger scope of each repository in the presentation layer itself.</li></ul><p>After almost 8 months of development and around 5 months of the app being in production, we are feeling the positive effects of adopting the new architecture. Developing new features has become a breeze; we are now deploying to production faster and with fewer bugs. We have removed code coupling in our code and improved code readability.</p><p>With the revamped architecture, we, as developers, are happy with our code and to that effect, we are also making our users happy by giving them requested features faster and with quality!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44aae0a3ea41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weeronline/our-approach-to-modularization-and-mvvm-44aae0a3ea41">Our approach to modularization and MVVM</a> was originally published in <a href="https://medium.com/weeronline">Weeronline</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>