<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Stojan Anastasov</title>
    <description>The latest articles on DEV Community by Stojan Anastasov (@s_anastasov).</description>
    <link>https://dev.to/s_anastasov</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F9931%2F8ad2dfce-2e97-4b5d-85f5-41365fb6809b.png</url>
      <title>DEV Community: Stojan Anastasov</title>
      <link>https://dev.to/s_anastasov</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/s_anastasov"/>
    <language>en</language>
    <item>
      <title>Modelling UI State on Android</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Fri, 29 Jan 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/modelling-ui-state-on-android-2d8o</link>
      <guid>https://dev.to/s_anastasov/modelling-ui-state-on-android-2d8o</guid>
      <description>&lt;p&gt;The recommended approach from Google for Android development is holding the UI state in a &lt;code&gt;ViewModel&lt;/code&gt; and having the &lt;code&gt;View&lt;/code&gt; observe it. To achieve that one can use &lt;code&gt;LiveData&lt;/code&gt;, &lt;code&gt;StateFlow&lt;/code&gt;, &lt;code&gt;RxJava&lt;/code&gt; or a similar tool. But how to model the UI state? Use a data class or a sealed class? Use one observable property or many? I will describe the tradeoffs between the approaches and present a tool to help you decide which one to use. This article is heavily inspired by &lt;a href="https://guide.elm-lang.org/appendix/types_as_sets.html"&gt;Types as Sets&lt;/a&gt; from the Elm guide.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--snloXRGi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://lordraydenmk.github.io/images/posts/arch.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--snloXRGi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://lordraydenmk.github.io/images/posts/arch.jpg" alt="Architecture"&gt;&lt;/a&gt; Photo by &lt;a href="https://unsplash.com/@marcojodoin"&gt;Marc-Olivier Jodoin&lt;/a&gt; on &lt;a href="https://unsplash.com/s/photos/architecture"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Types as sets
&lt;/h2&gt;

&lt;p&gt;By &lt;a href="https://www.youtube.com/watch?v=x1FU3e0sT1I"&gt;Making Data Structure&lt;/a&gt; we can make sure the &lt;em&gt;possible values in code&lt;/em&gt; exactly match the &lt;em&gt;valid values in real life&lt;/em&gt;. Doing that helps to avoid a whole class of bugs related to invalid data. To achieve that, first we need to understand the relationship between Types and Sets.&lt;/p&gt;

&lt;p&gt;We can think of Types as sets of values, they contain unique elements and there is no ordering between them. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Nothing&lt;/code&gt; - the empty set, it contains no elements&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Unit&lt;/code&gt; - the singleton set, it contains one element - &lt;code&gt;Unit&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Boolean&lt;/code&gt; - contains the elements &lt;code&gt;true&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Int&lt;/code&gt; - contains the elements: … &lt;code&gt;-2&lt;/code&gt;, &lt;code&gt;-1&lt;/code&gt;, &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;2&lt;/code&gt; …&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Float&lt;/code&gt; - contains the elements: &lt;code&gt;0.1&lt;/code&gt;, &lt;code&gt;0.01&lt;/code&gt;, &lt;code&gt;1.0&lt;/code&gt; ….&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;String&lt;/code&gt; - contains the elements: &lt;code&gt;""&lt;/code&gt;, &lt;code&gt;"a"&lt;/code&gt;, &lt;code&gt;"b"&lt;/code&gt;, &lt;code&gt;"Kotlin"&lt;/code&gt;, &lt;code&gt;"Android"&lt;/code&gt;, &lt;code&gt;"Hello world!"&lt;/code&gt;…&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So when you write: &lt;code&gt;val x: Boolean&lt;/code&gt; it means &lt;code&gt;x&lt;/code&gt; belongs to the set of &lt;code&gt;Boolean&lt;/code&gt; values and can be either &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cardinality
&lt;/h2&gt;

&lt;p&gt;In Mathematics, &lt;a href="https://en.wikipedia.org/wiki/Cardinality"&gt;Cardinality&lt;/a&gt; is the measure of “number of elements” of a Set. For example the set of &lt;code&gt;Boolean&lt;/code&gt; contains the elements &lt;code&gt;[true, false]&lt;/code&gt; so it has a cardinality = 2.&lt;/p&gt;

&lt;p&gt;Let’s take a look at the cardinality of the sets mentioned above:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Nothing&lt;/code&gt; - 0&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Unit&lt;/code&gt; - 1&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Boolean&lt;/code&gt; - 2&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Short&lt;/code&gt; - 65535&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Int&lt;/code&gt; - ∞&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Float&lt;/code&gt; - ∞&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;String&lt;/code&gt;- ∞&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : The cardinality of &lt;code&gt;Int&lt;/code&gt; and &lt;code&gt;Float&lt;/code&gt; is not exactly infinity, it’s 2^32 however that is a huge number.&lt;/p&gt;

&lt;p&gt;When building apps, we use built-in types and create custom types using constructs like data classes and sealed classes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Product Types (*)
&lt;/h2&gt;

&lt;p&gt;One flavor of product types in Kotlin are &lt;code&gt;Pair&lt;/code&gt; and &lt;code&gt;Triple&lt;/code&gt;. Let’s take a look at their cardinality:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Pair&amp;lt;Unit, Boolean&amp;gt;&lt;/code&gt; - cardinality(Unit) * cardinality(Boolean) = 1 * 2 = 2&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Pair&amp;lt;Boolean, Boolean&amp;gt;&lt;/code&gt; - 2 * 2 = 4&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;Pair&amp;lt;Unit, Boolean&amp;gt;&lt;/code&gt; contains the elements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Pair(Unit, false)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Pair(Unit, true)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Triple&amp;lt;Unit, Boolean, Boolean&lt;/code&gt;&amp;gt; = 1 * 2 * 2 = 4&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Pair&amp;lt;Int, Int&amp;gt;&lt;/code&gt; = cardinality(Int) * cardinality(Int) = ∞ * ∞ = ∞&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Well, that escalated quickly.&lt;/p&gt;

&lt;p&gt;When combining types with &lt;code&gt;Pair/Triple&lt;/code&gt; their cardinalities multiply (hence the name Product Types).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Pair/Triple&lt;/code&gt; are the generic version of data classes with 2 and 3 properties respectively.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;data class User(val emailVerified: Boolean, val isAdmin: Boolean)&lt;/code&gt; has the same cardinality as &lt;code&gt;Pair&amp;lt;Boolean, Boolean&amp;gt;&lt;/code&gt;, 4. The elements are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;User(false, false)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;User(false, true)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;User(true, false)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;User(true, true)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Sum Types (+)
&lt;/h2&gt;

&lt;p&gt;In Kotlin we use sealed classes to implement Sum types. When combining types using sealed classes, the total cardinality is equal to the sum of the cardinality of the members. Some examples are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed class NotificationSetting
object Disabled : NotificationSettings() // an object has one element -&amp;gt; cardinality = 1
data class Enabled(val pushEnabled: Boolean, val emailEnabled: Boolean) : NotificationSettings()

// cardinality = cardinality (Disabled) + cardinality(Enabled)
// cardinality = 1 + (2 * 2)
// cardinality = 1 + 4 = 5

sealed class Location
object Unknown : Location()
data class Somewhere(val lat: Float, val lng: Float) : Location()

// cardinality = cardinality (Unknown) + cardinality(Somewhere)
// cardinality = 1 + (∞ * ∞)
// cardinality = 1 + ∞ = ∞

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Nullable Types
&lt;/h3&gt;

&lt;p&gt;Another way to model the &lt;code&gt;Location&lt;/code&gt; type is using nullable types &lt;code&gt;data class Location(val lat: Float, val lng: Float)&lt;/code&gt; and represent it as: &lt;code&gt;val location: Location?&lt;/code&gt;. In this scenario we use &lt;code&gt;null&lt;/code&gt; when the location is unknown. These two representations have the same cardinality and we can convert between them without any information loss. A few more examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Unit?&lt;/code&gt; - cardinality = 2 (1 + cardinality(Unit))&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Boolean?&lt;/code&gt; - 3 (1 + cardinality(Boolean))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The elements of a nullable type &lt;code&gt;A?&lt;/code&gt; are &lt;code&gt;null&lt;/code&gt; + the elements of the original type &lt;code&gt;A&lt;/code&gt;. The cardinality of a nullable type is 1 + the cardinality of the original type.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enums
&lt;/h3&gt;

&lt;p&gt;Enums are another way of representing Sum types in Kotlin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum class Color { RED, YELLOW, GREEN }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The cardinality of &lt;code&gt;Color&lt;/code&gt; is equal to the number of elements, in this case 3. An alternative representation using a sealed class is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed class Color
object Red : Color()
object Yellow : Color()
object Green : Color()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and it has the same cardinality - 3.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why does it matter
&lt;/h2&gt;

&lt;p&gt;Thinking about Types as Sets and their cardinality helps with data modelling to avoid a whole class of bugs related to Invalid Data. Let’s say we are modelling a traffic light. The possible colors are: red, yellow and green. To represent them in code we could use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;a &lt;code&gt;String&lt;/code&gt; where &lt;code&gt;"red"&lt;/code&gt;, &lt;code&gt;"yellow"&lt;/code&gt; and &lt;code&gt;"green"&lt;/code&gt; are the valid options and everything else is invalid data. But then the user types &lt;code&gt;"rad"&lt;/code&gt; instead of red and we have an issue. Or &lt;code&gt;"yelow"&lt;/code&gt; or &lt;code&gt;"RED"&lt;/code&gt;. Should all functions validate their arguments? Should all functions have tests? The root cause of the issue here is cardinality. A String has cardinality of ∞ while the our problem has 3. There are ∞ - 3 possible invalid values.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;a data class &lt;code&gt;data class Color(val isRed: Boolean, val isYellow: Boolean, val isGreen: Boolean)&lt;/code&gt; - here &lt;code&gt;Color(true, false, false)&lt;/code&gt; represents red. Yet this still leaves room for invalid data e.g. &lt;code&gt;Color(true, true, true)&lt;/code&gt;. Again you would need checks and tests to ensure values are valid. The cardinality of the data class &lt;code&gt;Color&lt;/code&gt; is 8 and it has 8 - 3 = 5 illegal values. It’s much better then the &lt;code&gt;String&lt;/code&gt;, but we can still improve it.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;an enum - &lt;code&gt;enum class Color { RED, YELLOW, GREEN }&lt;/code&gt; - this has a cardinality = 3. It matches exactly the possible valid values of the problem. Illegal values are now impossible, so there is no need for tests that check data validity.&lt;/p&gt;

&lt;p&gt;By modelling the data in a way that rules out illegal values, the resulting code will also end up shorter, more clear and easier to test.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Make sure the set of possible values in code match the set of valid values of the problem and a lot of issues disappear.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Exposing State from a ViewModel
&lt;/h2&gt;

&lt;p&gt;The task:&lt;/p&gt;

&lt;p&gt;Build an app that calls a traffic light endpoint and shows the color of the traffic light (red, yellow or green). During the network call show a &lt;code&gt;ProgressBar&lt;/code&gt;. On success show a &lt;code&gt;View&lt;/code&gt; with the color and in case of an error show a &lt;code&gt;TextView&lt;/code&gt; with a generic text. Only one view is visible at a time and there is no possibility to retry errors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TrafficLightViewModel : ViewModel() {

    val state: LiveData&amp;lt;TrafficLightState&amp;gt; = TODO()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I will represent the color as an enum with three values. How should the type &lt;code&gt;TrafficLightState&lt;/code&gt; look like?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data class TrafficLightState(
    val isLoading: Boolean, 
    val isError: Boolean, 
    val color: Color?
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;one way is a data class with three properties. Yet this has possible invalid states e.g. &lt;code&gt;TrafficLightState(true, true, Color.RED)&lt;/code&gt;. Both error and loading are true. Showing both the &lt;code&gt;ProgressBar&lt;/code&gt; and the error &lt;code&gt;TextView&lt;/code&gt; should not be possible in the UI. We also have a Color which is impossible in case of an error. The cardinality of &lt;code&gt;TrafficLightState&lt;/code&gt; is 2 (Boolean) * 2 (Boolean) * 4 (Color?) = 16.&lt;/p&gt;

&lt;p&gt;What about using many observable properties?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TrafficLightViewModel : ViewModel() {

    val loading: LiveData&amp;lt;Boolean&amp;gt; = TODO()

    val error: LiveData&amp;lt;Boolean&amp;gt; = TODO()

    val color: LiveData&amp;lt;Color?&amp;gt; = TODO()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This has a cardinality of 2 (Boolean) * 2 (Boolean) * 4 (Color?) = 16. it has the same cardinality as the data class approach and enables illegal values.&lt;/p&gt;

&lt;p&gt;Another approach is using a sealed class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sealed class TrafficLightState
object Loading : TrafficLightState()
object Error : TrafficLightState()
data class Success(val color: Color) : TrafficLightState()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which has a cardinality of 1 (Loading) + 1 (Error) + 3 (Success) = 5 which exactly matches the possible states of the problem:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;during the network call: &lt;code&gt;Loading&lt;/code&gt; and show the &lt;code&gt;ProgressBar&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;if the network call fails: &lt;code&gt;Error&lt;/code&gt; and show a &lt;code&gt;TextView&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;on success: &lt;code&gt;Success&lt;/code&gt; and show a view with the corresponding color&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are all valid approaches and when designing your UI state. But only one of them matches exactly the possible valid states of the problem. To eliminate bugs, simplify code and reduce the number of tests, use that one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;To model problems in code we use built-in types like: &lt;code&gt;Boolean&lt;/code&gt;, &lt;code&gt;Int&lt;/code&gt;, &lt;code&gt;String&lt;/code&gt;… and in Kotlin we also create custom types using constructs like data class and sealed class. Different language constructs have different effects on the cardinality of the model. Reduce the number of invalid states by picking the right combination. That will results in simpler and more robust code.&lt;/p&gt;

&lt;p&gt;Thanks &lt;a href="https://twitter.com/GaelMarhic"&gt;Gaël&lt;/a&gt; for the review.&lt;/p&gt;

</description>
      <category>android</category>
      <category>kotlin</category>
      <category>functional</category>
    </item>
    <item>
      <title>Unit Tests and Concurrency</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Wed, 06 Jan 2021 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/unit-tests-and-concurrency-3pcp</link>
      <guid>https://dev.to/s_anastasov/unit-tests-and-concurrency-3pcp</guid>
      <description>&lt;p&gt;Once Retrofit added RxJava support, RxJava became my go-to concurrency framework for writing Android apps. One of the great things about RxJava is the excellent testing support. It includes &lt;code&gt;TestObserver&lt;/code&gt;, &lt;code&gt;TestScheduler&lt;/code&gt;, &lt;code&gt;RxJavaPlugins&lt;/code&gt; so you can switch your schedulers in tests.&lt;/p&gt;

&lt;p&gt;A common approach in testing RxJava code is using a &lt;a href="https://github.com/Plastix/RxSchedulerRule"&gt;JUnit rule&lt;/a&gt; that replaces the &lt;code&gt;Scheduler&lt;/code&gt; pools with &lt;code&gt;Schedulers.trampoline()&lt;/code&gt; before tests are run and resets them to the original thread pools after the tests. This makes the whole Observable chain runs on a single thread, the same thread the test runs on, which means we can write assertions without worrying about concurrency. However the production code usually is not single threaded. IO operations are done on the IO thread pool, views are updated on the main thread and everything else happens on the computation pool. By using different schedulers in the tests and using a different strategy (single threaded) we make those unit tests useless in catching concurrency issues.&lt;/p&gt;

&lt;h2&gt;
  
  
  A real world scenario
&lt;/h2&gt;

&lt;p&gt;I was working on a side project. The screen consists of a &lt;code&gt;RecyclerView&lt;/code&gt; displaying a list of elements. To get the elements I need to perform two different API calls. The first API call returns a list with N elements, then for each item in the list I need to perform the second call. After combining the data I send it to the UI for displaying. Using RxJava this looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Emits Loading then Content or Problem
private fun requestData(): Observable&amp;lt;ViewState&amp;gt; =
    service.firstApiCall()
        .observeOn(Schedulers.computation())
        .map { it.message }
        .flatMap(this::secondApiCall)
        .map&amp;lt;ViewState&amp;gt; { ViewState.Content(it) }
        .startWith(Single.just(ViewState.Loading))
        .onErrorReturn { ViewState.Problem }
        .toObservable()

// Concurrently executes secondApiCall for each element in list. 
// Transforms the result to ViewEntity, combines everything in a list
private fun secondApiCall(list: List&amp;lt;String&amp;gt;): Single&amp;lt;List&amp;lt;ViewEntity&amp;gt;&amp;gt; =
    Observable.fromIterable(list)
        .concatMapEager { item -&amp;gt;
            service.secondEndpoint(item)
                .observeOn(Schedulers.computation())
                .map { it.message }
                .map { ViewEntity(item, it.toHttpUrl()) }
                .onErrorReturn { DogViewEntity(item, null) }
                .toObservable()
        }
        .toList()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since the list is 15-20 elements, I am using &lt;code&gt;concatMapEager&lt;/code&gt; to execute the API calls for the second endpoint concurrently while maintaining the order of the elements. This worked great and I wrote my unit tests using the real schedulers. RxJava has amazing testing support that enables this. Thanks &lt;a href="https://twitter.com/vergauwen_simon"&gt;Simon Vergauwen&lt;/a&gt; for the tips on how to do that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
fun `execute - first call succeeds, one failed call to #2 - one full item, one item with default value`() {
    val items = listOf("Item 1" to "https://item1.jpg", "Item 2" to "invalid url")
    val service = successService(items) // Fake implementation of a retrofit service, always returns success

    val viewModel = ViewModel(service)

    val expected = listOf(
        ViewEntity("Item 1", "https://item1.jpg".toHttpUrl()),
        ViewEntity("Item 2", null)
    )
    viewModel.state
        .test()
        .also { viewModel.execute() }
        .awaitCount(2) // (0) Loading, (1) Content
        .assertValueAt(1, Content(expected))
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;awaitCount(2)&lt;/code&gt; makes sure the assertions after it are ran only after it gets at least 2 items.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Refactor
&lt;/h2&gt;

&lt;p&gt;This worked reasonably well, however I decided to try and optimise it further.&lt;/p&gt;

&lt;p&gt;My current code would:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;start with a progress bar&lt;/li&gt;
&lt;li&gt;do API call #1&lt;/li&gt;
&lt;li&gt;do API call #2 N times concurrently&lt;/li&gt;
&lt;li&gt;combine the results&lt;/li&gt;
&lt;li&gt;show the full list in the UI&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What if we display the data as it becomes available.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;start with a progress bar&lt;/li&gt;
&lt;li&gt;do API call #1&lt;/li&gt;
&lt;li&gt;show the data from API call #1 in the UI&lt;/li&gt;
&lt;li&gt;do API calls #2 N times concurrently without displaying progress&lt;/li&gt;
&lt;li&gt;update the UI N times as the API calls for #2 are completing&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I was already using &lt;code&gt;ListAdapter&lt;/code&gt; which has built-in diffing support. I can send an updated list and it will do it’s magic to update the changed elements only.&lt;/p&gt;

&lt;h2&gt;
  
  
  Improving the solution
&lt;/h2&gt;

&lt;p&gt;The original code was written as a single Rx chain. It emits a &lt;code&gt;Loading&lt;/code&gt; state, then does the API calls, combines the data and emits a &lt;code&gt;Content&lt;/code&gt; state (or an &lt;code&gt;Error&lt;/code&gt; state in case of failure). I modified it to: emit a &lt;code&gt;Content&lt;/code&gt; state containing the list of elements from API call #1 right after the call is done. The data from call #2 had some default values for the time being. After each invocation of call #2, get the current state, update the element and emit a new &lt;code&gt;Content&lt;/code&gt; state. I ran my tests and they failed as expected. I updated the tests to include the intermittent states (the changes caused emitting partial &lt;code&gt;Content&lt;/code&gt; states). Ran the tests again, two worked, one failed. Ran again, all green.&lt;/p&gt;

&lt;p&gt;The updated test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
fun `execute - first call succeeds, one failed call to #2 - one full item, one item with default value`() {
    val items = listOf("Item 1" to "https://item1.jpg", "Item 2" to "invalid url")
    val service = successService(items)

    val viewModel = ViewModel(service)

    val expected = listOf(
        ViewEntity("Item 1", "https://item1.jpg".toHttpUrl()),
        ViewEntity("Item 2", null)
    )
    viewModel.state
        .test()
        .also { viewModel.execute() }
        .awaitCount(4) // (0) Loading, (1) Content, (2) Content (3) Content
        .assertValueAt(3, Content(expected))
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the only changes in the test are: the argument to &lt;code&gt;awaitCount&lt;/code&gt; went from 2 to 4 (to account for the intermittent &lt;code&gt;Content&lt;/code&gt; values) and the final result is now at index 3.&lt;/p&gt;

&lt;p&gt;My refactoring made my tests flaky. Depending of the scheduling and the order of the requests for API call #2 I would get the correct or wrong result. My code had a concurrency issue.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--h_M1TAsN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://lordraydenmk.github.io/images/posts/concurrency.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--h_M1TAsN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://lordraydenmk.github.io/images/posts/concurrency.jpg" alt="Multithreading theory VS practice"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My state lives in a serialized &lt;code&gt;BehaviorSubject&lt;/code&gt;. I would update the state by reading it from the subject, create an immutable copy of the updated state, write back the updated state to the &lt;code&gt;Subject&lt;/code&gt;. However this is NOT thread safe. Since the state updates happened on the computation pool, multiple threads could do it at the same time. This resulted in inconsistent state, the results of some API calls would get overwritten by the next call.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;When testing RxJava code, you do NOT have to replace all schedulers with Trampoline. Doing that will make you miss possible concurrency issues. Using the real schedulers can help you catch those concurrency issues. It is not a perfect solution, but better than nothing. Don’t replace all schedulers with trampoline by default, make it a conscious choice to do so, or not do it.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href="https://twitter.com/marcellogalhard"&gt;Marcello&lt;/a&gt; and &lt;a href="https://twitter.com/GaelMarhic"&gt;Gaël&lt;/a&gt; for the review of this post.&lt;/p&gt;

</description>
      <category>android</category>
      <category>testing</category>
      <category>rxjava</category>
      <category>kotlin</category>
    </item>
    <item>
      <title>Fragments, ViewBinding and memory leaks</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Fri, 30 Oct 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/fragments-viewbinding-and-memory-leaks-3kn1</link>
      <guid>https://dev.to/s_anastasov/fragments-viewbinding-and-memory-leaks-3kn1</guid>
      <description>&lt;p&gt;As an Android engineer one of the basic things you need to do is bind the views (written in XML) with Kotlin/Java code. You can do this with the basic primitive -&lt;code&gt;findViewById()&lt;/code&gt;, using a library like &lt;a href="https://jakewharton.github.io/butterknife/" rel="noopener noreferrer"&gt;ButterKnife&lt;/a&gt;, using a compiler plugin like Kotlin Android Extensions or starting with Android Studio/AGP 3.6 &lt;a href="https://developer.android.com/topic/libraries/view-binding" rel="noopener noreferrer"&gt;ViewBinding&lt;/a&gt;. There are a few other options out there but in my experience these are the most common.&lt;/p&gt;

&lt;p&gt;The Kotlin Android Extensions plugin will be &lt;a href="https://youtrack.jetbrains.com/issue/KT-42121" rel="noopener noreferrer"&gt;deprecated&lt;/a&gt; (except the &lt;code&gt;@Parcelize&lt;/code&gt; functionality) in favor of ViewBinding soon. I see this as a positive change, but not everyone shares my opinion. One of the common arguments against ViewBinding (according to a comment in the ticket, a discussion on reddit and a friend of mine) is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;ViewBinding introduces memory leaks in Fragments.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s take a look into the usage example from the official docs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The fragment outlives the view, which means that if we forget to clear the binding reference in &lt;code&gt;onDestroyView&lt;/code&gt; this will cause a memory leak. Now I do agree that this is error prone, you have to remember to clear the binding reference in each fragment you create. However this problem is not inherent to ViewBinding, but to this kind of usage. The problem here is: a component with a larger scope (the fragment) keeps a reference to a component with a smaller scope (the binding).&lt;/p&gt;

&lt;p&gt;Clearing the reference is a workaround, the proper solution is to move the reference to the correct scope:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private val viewModel by viewModels&amp;lt;ProfileViewModel&amp;gt;()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val binding = ResultProfileBinding.bind(view)

    TODO("Set any (click) listeners")

    viewModel.liveData.observe(viewLifecycleOwner) { data -&amp;gt;
        TODO("Bind the data to views")
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you move the binding reference from the &lt;code&gt;Fragment&lt;/code&gt; scope to a function scope, you don’t have to worry about clearing it because the function scope is smaller then the view scope. Now this does assume the MVVM pattern for the UI layer.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Flordraydenmk.github.io%2Fimages%2Fposts%2Fclear-reference.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Flordraydenmk.github.io%2Fimages%2Fposts%2Fclear-reference.jpg" alt="You don't have to clear a reference that doesn't exist"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another argument against ViewBinding that I have seen is that is more code, you have to type &lt;code&gt;binding.view&lt;/code&gt; instead of just &lt;code&gt;view&lt;/code&gt; (using kotlin android extensions):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// kotlin-android-extensions
viewModel.liveData.observe(viewLifecycleOwner) { data -&amp;gt;
    textView.text = data.title
    imageView.load(data.imageUrl)
}

// view-binding
val binding = ResultProfileBinding.bind(view)

viewModel.liveData.observe(viewLifecycleOwner) { data -&amp;gt;
    binding.textView.text = data.title
    binding.imageView.load(data.imageUrl)
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To ease the pain here you can use kotlin’s scoping function &lt;code&gt;with&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// view-binding
val binding = ResultProfileBinding.bind(view)

viewModel.liveData.observe(viewLifecycleOwner) { data -&amp;gt;
    with(binding) {
        textView.text = data.title
        imageView.load(data.imageUrl)
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and the repetitive &lt;code&gt;binding&lt;/code&gt; is gone. The more views you have, the better this scales - you only write &lt;code&gt;with(binding)&lt;/code&gt; once.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using ViewBinding with Fragments can be error prone, but it doesn’t have to be. The solution is moving the reference to the binding from a Fragment scope to a local function scope.&lt;/p&gt;

</description>
      <category>android</category>
      <category>viewbinding</category>
      <category>kotlin</category>
    </item>
    <item>
      <title>Communicating with your Lifecycle Owner using RxJava</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Tue, 08 Sep 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/communicating-with-your-lifecycle-owner-using-rxjava-48e5</link>
      <guid>https://dev.to/s_anastasov/communicating-with-your-lifecycle-owner-using-rxjava-48e5</guid>
      <description>&lt;p&gt;Google introduced Jetpack, a family of opinionated libraries to make Android development easier a few years ago. One of the core classes in Jetpack is &lt;code&gt;LiveData&lt;/code&gt; - an observable, lifecycle aware data holder. The typical use case is having a &lt;code&gt;ViewModel&lt;/code&gt; that exposes &lt;code&gt;LiveData&lt;/code&gt; as a property, and observing it from your lifecycle owner, a &lt;code&gt;Fragment&lt;/code&gt; or an &lt;code&gt;Activity&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A typical usage would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data class MyState(val value: String)

class MyViewModel : ViewModel {

    private val _state = MutableLiveData&amp;lt;MyState&amp;gt;()
    val state: LiveData&amp;lt;MyState&amp;gt;
    get() = _state
}

class MyFragment : Fragment {

    val viewModel by viewModels&amp;lt;MyViewModel&amp;gt;()

    override fun onViewCreated() {
        viewModel.state.observe(this, Observer(::handleState))
    }

    private fun handleState(state: MySate): Unit = TODO()
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There are multiple benefits of using &lt;code&gt;LiveData&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your observer is notified when the data changes&lt;/li&gt;
&lt;li&gt;The observer is only notified of changes when it’s active&lt;/li&gt;
&lt;li&gt;Observers are notified when they become active again, like entering into foreground etc&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Check the &lt;a href="https://developer.android.com/topic/libraries/architecture/livedata"&gt;LiveData&lt;/a&gt; docs for all benefits.&lt;/p&gt;

&lt;h2&gt;
  
  
  LiveData and Events
&lt;/h2&gt;

&lt;p&gt;In situations like showing a &lt;code&gt;Snackbar&lt;/code&gt;/dialog or navigating to a different &lt;code&gt;Activity/Fragment&lt;/code&gt; the &lt;code&gt;ViewModel&lt;/code&gt; also needs to notify the &lt;code&gt;LifecycleOwner&lt;/code&gt;. A plain old &lt;code&gt;LiveData&lt;/code&gt; doesn’t work well here because it caches the last item. As a workaround, in the official Android architecture samples there is a &lt;code&gt;SingleLiveEvent&lt;/code&gt; implementation of &lt;code&gt;LiveData&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data Layer
&lt;/h2&gt;

&lt;p&gt;But what about the rest of the app? You can use &lt;code&gt;LiveData&lt;/code&gt; in your data layer, in fact Room, the persistence library from Jetpack, support &lt;code&gt;LiveData&lt;/code&gt; as the return type natively. However while using &lt;code&gt;LiveData&lt;/code&gt; across all the layer in the app is possible, it is less than ideal. The operations are always executed on the Main Thread and it comes with limited number of transformation functions compared to &lt;code&gt;RxJava&lt;/code&gt; or &lt;code&gt;Flow&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To fix this problem &lt;code&gt;LiveData&lt;/code&gt; comes with adapters for both &lt;code&gt;RxJava&lt;/code&gt; and &lt;code&gt;Flow&lt;/code&gt; from KotlinX Coroutines. This means developers can use &lt;code&gt;RxJava&lt;/code&gt; or &lt;code&gt;Flow&lt;/code&gt; in their data layer and convert to &lt;code&gt;LiveData&lt;/code&gt; in the &lt;code&gt;ViewModel&lt;/code&gt; benefiting from the lifecycle awareness.&lt;/p&gt;

&lt;h2&gt;
  
  
  State and RxJava
&lt;/h2&gt;

&lt;p&gt;I was working on a sample app last week using the Marvel API, you can check the full code on &lt;a href="https://github.com/LordRaydenMK/SuperheroesAndroid"&gt;Github&lt;/a&gt;. It uses a fully reactive architecture powered by RxJava. My initial approach was to use &lt;code&gt;LiveData&lt;/code&gt; for the &lt;code&gt;ViewModel&lt;/code&gt; -&amp;gt; &lt;code&gt;Fragment&lt;/code&gt; communication. However I also wanted to benefit from the &lt;code&gt;RxJava&lt;/code&gt; excellent testing support, so I decided to try and do what &lt;code&gt;LiveData&lt;/code&gt; does using &lt;code&gt;RxJava&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For observing state, RxJava offer &lt;code&gt;BehaviorSubject&lt;/code&gt;, a &lt;code&gt;Subject&lt;/code&gt; that caches the last value it observer and emits it to each subscribed &lt;code&gt;Observer&lt;/code&gt;. That takes care of the caching of the last value and observing changes. For observing on the Main Thread there is &lt;code&gt;RxAndroid&lt;/code&gt;. What about the lifecycle part. To take care of that I created a &lt;a href="https://github.com/LordRaydenMK/SuperheroesAndroid/blob/7e627c1aa1b01c42b8a0c3baec7c32b70dcc6d8e/app/src/main/java/io/github/lordraydenmk/superheroesapp/common/lifecycleDisposable.kt"&gt;utility class&lt;/a&gt;, built atop &lt;code&gt;LifecycleOwner&lt;/code&gt; to help me dispose of the subscription at the right lifecycle callback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LifecycleDisposable(
    private val disposable: Disposable
) : DefaultLifecycleObserver {

    override fun onDestroy(owner: LifecycleOwner) {
        disposable.dispose()
        super.onDestroy(owner)
    }
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;the code using this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class RxViewModel : ViewModel() {

    private val _state = BehaviorSubject.create&amp;lt;MyState&amp;gt;()
    val state: Observable&amp;lt;MyState&amp;gt;
    get() = _state
}

class RxFragment : Fragment() {

    val viewModel by viewModels&amp;lt;MyViewModel&amp;gt;()

    fun onViewCreated() {
        viewModel.state
            .subscribe(::handleState)
            .autoDispose() // extension function, check the Github link
    }

    private fun handleState(state: MySate) = TODO()
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Unlike &lt;code&gt;LiveData&lt;/code&gt;, this starts observing in &lt;code&gt;onViewCreated&lt;/code&gt; and unsubscribes in &lt;code&gt;onDestroyView&lt;/code&gt;. The code would be similar to subscribe in &lt;code&gt;onStart&lt;/code&gt; and stop observing in &lt;code&gt;onStop&lt;/code&gt;, however in my experience (and I could be wrong) updating view state while the view is not active never caused me problems.&lt;/p&gt;

&lt;h2&gt;
  
  
  Events and RxJava
&lt;/h2&gt;

&lt;p&gt;Events are a bit different than state. The main requirement is to be delivered exactly once (they are consumable). Another important requirement is to be delivered ONLY when the view is active (between &lt;code&gt;onStart&lt;/code&gt; and &lt;code&gt;onStop&lt;/code&gt;). My first attempt was using &lt;code&gt;UnicastSubject&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A Subject that queues up events until a single Observer subscribes to it, replays those events to it until the Observer catches up and then switches to relaying events live to this single Observer until this UnicastSubject terminates or the Observer unsubscribes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;however that didn’t work out well. The queuing of events when there was no observers was working great. Upon subscription all events would be delivered. When there was a subscriber events were getting delivered. The problem was when the subscriber unsubscribes and a new subscriber tries to subscribe (&lt;code&gt;onStart&lt;/code&gt; and &lt;code&gt;onStop&lt;/code&gt; can be triggered multiple times). That led me to &lt;a href="https://github.com/akarnokd/RxJavaExtensions#unicastworksubject"&gt;UnicastWorkSubject&lt;/a&gt; from &lt;code&gt;RxJavaExtensions&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A Subject variant that buffers items and allows one Observer to consume it at a time, but unlike UnicastSubject, once the previous Observer disposes, a new Observer can subscribe and resume consuming the items.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which was exactly what I needed. For the lifecycle part, again I turned to &lt;code&gt;LifecycleObserver&lt;/code&gt; and created:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class EffectsObserver&amp;lt;E&amp;gt;(
    private val effects: Observable&amp;lt;E&amp;gt;,
    private val executeEffect: (E) -&amp;gt; Unit
) : DefaultLifecycleObserver {

    private var disposable: Disposable? = null

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        disposable = effects.flatMap {
            Observable.fromCallable { executeEffect(it) }
        }.subscribe()
    }

    override fun onStop(owner: LifecycleOwner) {
        disposable!!.dispose()
        super.onStop(owner)
    }
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;the usage looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycle.addObserver(EffectsObserver(viewModel.effects) { effect -&amp;gt;
        when (effect) {
            is NavigateToDetails -&amp;gt; TODO("Navigate")
        }
    })
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;this will make sure events such as navigation and showing a &lt;code&gt;Snackbar&lt;/code&gt; are queued when the app is in the background and happen only when the app is in foreground. It helps avoid the dreaded &lt;a href="https://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html"&gt;java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; when using this with a &lt;code&gt;Fragment&lt;/code&gt; it is important to register it in &lt;code&gt;onCreate&lt;/code&gt; (called exactly once) and not in &lt;code&gt;onViewCreated&lt;/code&gt; (may be called multiple times with fragments on the backstack).&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;You can emulate the way &lt;code&gt;LiveData&lt;/code&gt; works for &lt;code&gt;ViewModel&lt;/code&gt; -&amp;gt; &lt;code&gt;LifecycleOwner&lt;/code&gt; communication with &lt;code&gt;RxJava&lt;/code&gt;. However there are a few edge cases that you need to consider to do it right, like delivering events only when the &lt;code&gt;LifecycleOwner&lt;/code&gt; is active.&lt;/p&gt;

&lt;p&gt;If you have a different idea to achieve this leave a comment below. Happy coding!&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>android</category>
      <category>rxjava</category>
      <category>jetpack</category>
    </item>
    <item>
      <title>What is a Unit in unit testing </title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Thu, 29 Aug 2019 17:33:03 +0000</pubDate>
      <link>https://dev.to/s_anastasov/what-is-a-unit-in-unit-testing-3fe7</link>
      <guid>https://dev.to/s_anastasov/what-is-a-unit-in-unit-testing-3fe7</guid>
      <description>&lt;p&gt;What is a unit in unit testing? Is it a class, a function, a method, all of the above?&lt;/p&gt;

&lt;p&gt;Is it considered a unit test if we are testing a class without mocking all of the collaborators?&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>testing</category>
      <category>programming</category>
    </item>
    <item>
      <title>Side Effects and Composition</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Tue, 13 Aug 2019 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/side-effects-and-composition-153o</link>
      <guid>https://dev.to/s_anastasov/side-effects-and-composition-153o</guid>
      <description>&lt;p&gt;&lt;em&gt;Photo by &lt;a href="https://unsplash.com/@ryan_yoo"&gt;Ryan Yoo&lt;/a&gt; on &lt;a href="https://unsplash.com/search/photos/lego"&gt;Unsplash&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Functional Programing is amazing. It limits the things you can do (no nulls, no exceptions, no side effects…) and in return you get some benefits. Some benefits of FP are easy to explain and some not so much. I have been playing with FP for more than a year and only few weeks ago, when I started reading &lt;a href="https://www.manning.com/books/functional-programming-in-scala"&gt;Functional Programming in Scala&lt;/a&gt;, I found an amazing example the benefits of pure functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;Building a software for a Coffee Shop. For the initial MVP the requirements are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sell coffee&lt;/li&gt;
&lt;li&gt;Pay with a card&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;so the first draft of the code looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import coffee.*

fun buyCoffee(cc: CreditCard): Coffee {
    val cup = Coffee()
    cc.charge(cup.price)
    return cup
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;buyCoffee&lt;/code&gt; function receives a &lt;code&gt;CreditCard&lt;/code&gt; as an input and returns a &lt;code&gt;Coffee&lt;/code&gt; as an output. It creates a &lt;code&gt;Coffee&lt;/code&gt; object, then executes a charge and returns the &lt;code&gt;Coffee&lt;/code&gt; object.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testability
&lt;/h2&gt;

&lt;p&gt;The call &lt;code&gt;cc.charge&lt;/code&gt; uses an SDK/API to talk to the credit card company. It involves authorization, network call(s), persisting a record in the DB. The &lt;code&gt;buyCoffee&lt;/code&gt; function returns a &lt;code&gt;Coffee&lt;/code&gt; and the charging happens on the side hence the terms “side effect”.&lt;/p&gt;

&lt;p&gt;The side effect makes &lt;code&gt;buyCoffee&lt;/code&gt; hard to test in isolation. It would be nice (and cheaper) to run tests without actually talking to the credit card company and doing an actual charge. One could also argue that a &lt;code&gt;CreditCard&lt;/code&gt; should not know how it’s being charged.&lt;/p&gt;

&lt;p&gt;The testability problem can be fixed using Dependency Injection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun buyCoffee(cc: CreditCard, p: Payments): Coffee {
    val cup = Coffee()
    p.charge(cc, cup.price)
    return cup
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The logic of charging the credit card is extracted into the &lt;code&gt;Payments&lt;/code&gt; object. In production code the real &lt;code&gt;Payments&lt;/code&gt; implementation is used and a mock version is injected for tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  New requirements
&lt;/h2&gt;

&lt;p&gt;After a few weeks in business new requirements arrive. Some people buy more than one coffee so the next version of the software has additional requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Buying N coffees&lt;/li&gt;
&lt;li&gt;Single charge per Credit Card&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Composition
&lt;/h2&gt;

&lt;p&gt;The problem of buying a single coffee is already solved with &lt;code&gt;buyCoffee&lt;/code&gt;. It would be nice to reuse the code for one coffee to buy multiple coffees. The code is complex (could be), tested and debugged. Reusing the existing solution would also save time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Buying multiple coffees
&lt;/h2&gt;

&lt;p&gt;The first draft of &lt;code&gt;buyCoffees&lt;/code&gt; looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun buyCoffees(
    cc: CreditCard,
    p: Payments,
    n: Int
): List&amp;lt;Coffee&amp;gt; = List(n) { buyCoffee(cc, p) }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;it takes an additional parameter (compared to &lt;code&gt;buyCoffee&lt;/code&gt;), the number of coffees to buy. It returns a &lt;code&gt;List&amp;lt;Coffee&amp;gt;&lt;/code&gt; as expected. It uses &lt;code&gt;buyCoffee&lt;/code&gt; to fill a list with &lt;code&gt;n&lt;/code&gt; coffees.&lt;/p&gt;

&lt;p&gt;Unfortunately this code charges the credit card multiple times. That is bad both for the customer and the business (each transaction costs money).&lt;/p&gt;

&lt;p&gt;Again the problem is the side effect.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p.charge(cc, cup.price) // &amp;lt;-- Side effect
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Side Effects and Referential Transparency
&lt;/h2&gt;

&lt;p&gt;I mentioned the word &lt;em&gt;side effect&lt;/em&gt; multiple times. It’s time to explain what it is. A side effect is something that breaks referential transparency (RT). Which leads to the question: What is &lt;em&gt;referential transparency&lt;/em&gt;?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;An expression is called referentially transparent if it can be replaced with its corresponding value without changing the program’s behavior. - &lt;a href="https://en.wikipedia.org/wiki/Referential_transparency"&gt;Wikipedia&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  RT Example
&lt;/h3&gt;

&lt;p&gt;Given this version of &lt;code&gt;buyCoffee&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun buyCoffee(cc: CreditCard, p: Payments): Coffee {
    val cup = Coffee()
    p.charge(cc, cup.price)
    return cup
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;RT means that the &lt;code&gt;coffeeA&lt;/code&gt; can be replaced with it’s result a &lt;code&gt;Coffee&lt;/code&gt; without altering the program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val coffeeA: Coffee = buyCoffee(cc, p)  // returns Coffee()

val coffeeB: Coffee = Coffee()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;coffeeA&lt;/code&gt; and &lt;code&gt;coffeeB&lt;/code&gt; are not equivalent. With &lt;code&gt;coffeeA&lt;/code&gt; your credit card is charged, with &lt;code&gt;coffeeB&lt;/code&gt; you get a free coffee. That means &lt;code&gt;buyCoffee&lt;/code&gt; is not referentially transparent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solving the problem
&lt;/h2&gt;

&lt;p&gt;I can push the problem to the payment processor. I can create &lt;code&gt;BatchPaymentsProcessor&lt;/code&gt; that batches the payments before executing. This opens questions like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How long does it wait&lt;/li&gt;
&lt;li&gt;How many payments do it batch&lt;/li&gt;
&lt;li&gt;Is &lt;code&gt;buyCoffee&lt;/code&gt; responsible for indicating start/end batch&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;BatchPaymentsProcessor&lt;/code&gt; solves the code reuse problem but brings a whole set of new problems to the table. Can we do better?&lt;/p&gt;

&lt;h2&gt;
  
  
  Removing the Side Effect
&lt;/h2&gt;

&lt;p&gt;The side effect is preventing composition. If I remove it maybe I can regain composition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun buyCoffee(cc: CreditCard): Pair&amp;lt;Coffee, Charge&amp;gt; {
    val cup = Coffee()
    val charge = Charge(cc, cup.price)
    return Pair(cup, charge)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The side effect is gone now, so is the &lt;code&gt;Payments&lt;/code&gt; object. The return type changed to &lt;code&gt;Pair&amp;lt;Coffee, Charge&amp;gt;&lt;/code&gt;. A &lt;code&gt;Charge&lt;/code&gt; object is returned in addition to the &lt;code&gt;Coffee&lt;/code&gt;. The &lt;code&gt;Charge&lt;/code&gt; object is a pure value (a data class) indicating a charge should be made. The &lt;code&gt;Charge&lt;/code&gt; also contains the information needed to execute it like CC number and price.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;buyCoffee&lt;/code&gt; function is only responsible for creating the &lt;code&gt;Charge&lt;/code&gt; which is pure (no side effects). The responsibility of executing it is in another part of the program.&lt;/p&gt;

&lt;h2&gt;
  
  
  Combining charges
&lt;/h2&gt;

&lt;p&gt;Since &lt;code&gt;Charge&lt;/code&gt; is a regular value it can easily be combined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun combine(c1: Charge, c2: Charge): Charge =
    if (c1.cc == c2.cc) Charge(c1.cc, c1.price + c2.price)
    else throw IllegalArgumentException(
        "Can't combine charges with different cc"
    )
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;two charges, given they have the same Credit Card are combined by adding their price.&lt;/p&gt;

&lt;h2&gt;
  
  
  Buying multiple coffees revisited
&lt;/h2&gt;

&lt;p&gt;I can now implement the &lt;code&gt;buyCoffees&lt;/code&gt; function in terms of the pure &lt;code&gt;buyCoffee&lt;/code&gt; like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun buyCoffees(
    cc: CreditCard,
    n: Int
): Pair&amp;lt;List&amp;lt;Coffee&amp;gt;, Charge&amp;gt; {
    val purchases: List&amp;lt;Pair&amp;lt;Coffee, Charge&amp;gt;&amp;gt; =
        List(n) { buyCoffee(cc) }
    val (coffees, charges) = purchases.unzip()
    val charge = charges.reduce { c1, c2 -&amp;gt; combine(c1, c2) }
    return Pair(coffees, charge)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The return type is &lt;code&gt;Pair&amp;lt;List&amp;lt;Coffee, Charge&amp;gt;&amp;gt;&lt;/code&gt; containing a list of purchased coffees and a single charge for all of them. To create this the &lt;code&gt;buyCoffee&lt;/code&gt; function is used to populate a list with &lt;code&gt;n&lt;/code&gt; coffee items. The &lt;code&gt;unzip&lt;/code&gt; function is used to separate the coffees from the charges. Charges are combined using the &lt;code&gt;combine&lt;/code&gt; function defined above.&lt;/p&gt;

&lt;p&gt;Again the concern of executing the purchase is pushed to another part of the program.&lt;/p&gt;

&lt;p&gt;The benefits gained are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Better testability - the functions are testable without mocks&lt;/li&gt;
&lt;li&gt;Composition - the bigger function is implemented in terms of the smaller&lt;/li&gt;
&lt;li&gt;Separation of concerns - decision of purchase is separate of purchase execution&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By doing a simple thing like separating the decision of making a side effect and executing it the code is much more composable and reusable. This also improves testability as pure functions can be tested without using mocks. Being aware of the way side effects influence composition helps writing composable code.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>functional</category>
      <category>arrowkt</category>
    </item>
    <item>
      <title>Functional Hangman in Kotlin with Arrow (part 2)</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Tue, 25 Dec 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/functional-hangman-in-kotlin-with-arrow-part-2-3knl</link>
      <guid>https://dev.to/s_anastasov/functional-hangman-in-kotlin-with-arrow-part-2-3knl</guid>
      <description>&lt;p&gt;Converting a &lt;a href="https://dev.to/2018/functional-hangman-in-kotlin-with-arrow"&gt;Functional Hangman&lt;/a&gt; game from Scala (ZIO) to Kotlin (with Arrow) was a nice exercise. I enjoyed working on it and I learned a lot. When I asked for feedback on the &lt;a href="https://kotlinlang.slack.com/messages/C5UPMM0A0/"&gt;#arrow&lt;/a&gt; channel, one of the maintainers, &lt;a href="https://twitter.com/mLeandroBF"&gt;Leandro&lt;/a&gt; had an interesting suggestion. Instead of hard-coding the data type &lt;code&gt;IO&lt;/code&gt; I should try and make the program polymorphic and use &lt;code&gt;Kind&lt;/code&gt; instead. That means writing the code focusing on the domain logic, using abstractions, and deferring the decision for the concrete data type like &lt;code&gt;IO&lt;/code&gt; or &lt;code&gt;Single&lt;/code&gt; (from RxJava) until the main function.&lt;/p&gt;

&lt;h1&gt;
  
  
  The journey
&lt;/h1&gt;

&lt;p&gt;I was not familiar with that style of programming so I used this &lt;a href="https://arrow-kt.io/docs/patterns/polymorphic_programs/"&gt;example&lt;/a&gt; from the excellent Arrow documentation as a guide.&lt;/p&gt;

&lt;h2&gt;
  
  
  Writing to the the console
&lt;/h2&gt;

&lt;p&gt;In the previous article I used &lt;code&gt;IO&amp;lt;A&amp;gt;&lt;/code&gt; to interact with the console. &lt;code&gt;IO&amp;lt;A&amp;gt;&lt;/code&gt; represents an operation that can be executed lazily, fail with an exception (the exception is captured inside &lt;code&gt;IO&lt;/code&gt;), run forever or return a single &lt;code&gt;A&lt;/code&gt;. Let’s take a look at the original implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun putStrLn(line: String): IO&amp;lt;Unit&amp;gt; = IO { println(line) }

// Usage in main()
putStrLn("Hello world!").unsafeRunSync()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;putStrLn&lt;/code&gt; is a function that take a &lt;code&gt;String&lt;/code&gt; and return a &lt;code&gt;IO&amp;lt;Unit&amp;gt;&lt;/code&gt;. &lt;code&gt;IO&lt;/code&gt; takes a lambda that is lazily evaluated at the end of the world, when we call &lt;code&gt;unsafeRunSync()&lt;/code&gt;. If we want to achieve the same thing with &lt;code&gt;Single&lt;/code&gt; we could use &lt;code&gt;Single.fromCallable&lt;/code&gt; wrap our lambda and evaluate it in the main function when we call &lt;code&gt;subscribe()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun putStrLn(line: String): Single&amp;lt;Unit&amp;gt; = Single.fromCallable {
    println(line)
}

// Usage in main()
putStrLn("Hello World").subscribe()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here both&lt;code&gt;IO&lt;/code&gt; and &lt;code&gt;Single&lt;/code&gt; have something in common. A set of &lt;strong&gt;capabilities&lt;/strong&gt; like: &lt;strong&gt;lazy evaluation&lt;/strong&gt; , &lt;strong&gt;exception handling&lt;/strong&gt; , and &lt;strong&gt;running forever&lt;/strong&gt; or &lt;strong&gt;completing with a result&lt;/strong&gt; of type &lt;code&gt;A&lt;/code&gt;. &lt;code&gt;IO&lt;/code&gt; and &lt;code&gt;Single&lt;/code&gt; do a lot more, but for this use case, we want something as simple as possible that has the same capabilities. There is a type-class in Arrow that can do just that and it’s called &lt;code&gt;MonadDefer&lt;/code&gt;(&lt;a href="https://arrow-kt.io/docs/effects/monaddefer/"&gt;more info&lt;/a&gt;). After a few iterations, and feedback from the Arrow team, this is the code I came up with for printing to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun &amp;lt;F&amp;gt; putStrLn(M: MonadDefer&amp;lt;F&amp;gt;, line: String): Kind&amp;lt;F, Unit&amp;gt; = M.invoke {
    println(line)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;putStrLn&lt;/code&gt; function is generic with type &lt;code&gt;F&lt;/code&gt;, but not any &lt;code&gt;F&lt;/code&gt;. This &lt;code&gt;F&lt;/code&gt;, whatever it is, need to do certain things like &lt;strong&gt;lazy evaluation&lt;/strong&gt; and &lt;strong&gt;error handling&lt;/strong&gt;. This &lt;code&gt;F&lt;/code&gt; thing needs the &lt;strong&gt;capabilities&lt;/strong&gt; of &lt;code&gt;MonadDefer&lt;/code&gt;. The return value also needs a type parameter, and in Arrow we can do that by returning &lt;code&gt;Kind&amp;lt;F, SOMETHING&amp;gt;&lt;/code&gt;. In the case of printing to command line, that &lt;code&gt;SOMETHING&lt;/code&gt; is &lt;code&gt;Unit&lt;/code&gt; (no return value). &lt;code&gt;MonadDefer&lt;/code&gt; comes with an &lt;code&gt;invoke&lt;/code&gt; function that we can use to construct the value of &lt;code&gt;Kind&amp;lt;F, Unit&amp;gt;&lt;/code&gt;. We pass a lambda inside which will be lazily evaluated.&lt;/p&gt;

&lt;p&gt;Compared to the original implementation we have a few key differences:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a type parameter &lt;code&gt;F&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;one more parameter of type &lt;code&gt;MonadDefer&amp;lt;F&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;the return type is &lt;code&gt;Kind&amp;lt;F, Unit&amp;gt;&lt;/code&gt; instead of &lt;code&gt;IO&amp;lt;Unit&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now we can use this function to print something to the console. In order to do that, we need a data type that has the &lt;strong&gt;capabilities&lt;/strong&gt; of &lt;code&gt;MonadDefer&lt;/code&gt;. &lt;code&gt;IO&lt;/code&gt; can do that so we can use it. Arrow also ships with &lt;code&gt;SingleK&lt;/code&gt;, a wrapper for &lt;code&gt;Single&lt;/code&gt; that has the &lt;code&gt;MonadDefer&lt;/code&gt; capabilities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;putStrLn(IO.monadDefer(), "Hello World!").fix()
        .unsafeRunSync()

putStrLn(SingleK.monadDefer(), "Hello World!").fix()
        .single.subscribe()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Arrow also ships with &lt;code&gt;ObservableK&lt;/code&gt; for &lt;code&gt;Observable&lt;/code&gt;, &lt;code&gt;DeferredK&lt;/code&gt; for coroutines etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading from the console
&lt;/h2&gt;

&lt;p&gt;Reading from the console is similar to writing to it. We still need a type parameter &lt;code&gt;F&lt;/code&gt;, we still need to return &lt;code&gt;Kind&amp;lt;F, SOMETHING&amp;gt;&lt;/code&gt; and we need to perform the operation lazily with success or an error. &lt;code&gt;readLine()&lt;/code&gt; returns a nullable &lt;code&gt;String?&lt;/code&gt; and if that happens we need to signal an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original code
fun getStrLn(): IO&amp;lt;String&amp;gt; = IO { readLine() ?: throw IOException("Failed to read input!") }

// Polymorphic code
fun &amp;lt;F&amp;gt; getStrLn(M: MonadDefer&amp;lt;F&amp;gt;): Kind&amp;lt;F, String&amp;gt; = M.invoke {
    readLine() ?: throw IOException("Failed to read input!")
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Reading from the console #2
&lt;/h2&gt;

&lt;p&gt;I am throwing an &lt;code&gt;IOException&lt;/code&gt; to indicate failure. &lt;code&gt;IO&lt;/code&gt; would wrap that exception so it isn’t that bad. But there is a better way (thanks &lt;a href="https://twitter.com/mLeandroBF"&gt;Leandro&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;I convert the nullable &lt;code&gt;String?&lt;/code&gt; to an &lt;code&gt;Option&amp;lt;String&amp;gt;&lt;/code&gt;. Then I use &lt;code&gt;fold&lt;/code&gt; to check if the &lt;code&gt;Option&lt;/code&gt; has a value. If it’s empty I use &lt;code&gt;raiseError&lt;/code&gt; to create &lt;code&gt;MonadDefer&lt;/code&gt; which when evaluated returns an error. If it’s not empty I create a &lt;code&gt;MonadDefer&lt;/code&gt; that returns a &lt;code&gt;String&lt;/code&gt; using &lt;code&gt;just&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The key difference here is I am NOT throwing the &lt;code&gt;IOException&lt;/code&gt;. Using exceptions can be &lt;a href="http://java-performance.info/throwing-an-exception-in-java-is-very-slow/"&gt;expensive&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;M.defer&lt;/code&gt; here means the &lt;code&gt;readLine()&lt;/code&gt; happens lazily.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun &amp;lt;F&amp;gt; getStrLn(M: MonadDefer&amp;lt;F&amp;gt;): Kind&amp;lt;F, String&amp;gt; = M.defer {
    readLine().toOption()
            .fold(
                    { M.raiseError&amp;lt;String&amp;gt;(IOException("Failed to read input!")) },
                    { M.just(it) }
            )
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  The Hangman class
&lt;/h2&gt;

&lt;p&gt;The next step is to make the &lt;code&gt;Hangman&lt;/code&gt; class polymorphic. To do that I added a type parameter &lt;code&gt;F&lt;/code&gt; and property of the type &lt;code&gt;MonadDefer&amp;lt;F&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Hangman&amp;lt;F&amp;gt;(private val M: MonadDefer&amp;lt;F&amp;gt;) {
    ...
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Choosing a letter
&lt;/h2&gt;

&lt;p&gt;To make the &lt;code&gt;getChoice()&lt;/code&gt; function work in a polymorphic way we need a few changes. The return type changes from &lt;code&gt;IO&amp;lt;Char&amp;gt;&lt;/code&gt; to &lt;code&gt;Kind&amp;lt;F, Char&amp;gt;&lt;/code&gt;. &lt;code&gt;IO.binding&lt;/code&gt; becomes &lt;code&gt;M.binding&lt;/code&gt; (where &lt;code&gt;M&lt;/code&gt; is the property of type &lt;code&gt;MonadDefer&amp;lt;F&amp;gt;&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;getStrLn()&lt;/code&gt; and &lt;code&gt;putStrLn()&lt;/code&gt; also need &lt;code&gt;M&lt;/code&gt; as the parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun getChoice(): Kind&amp;lt;F, Char&amp;gt; = M.binding {
        putStrLn(M, "Please enter a letter").bind()
        val line = getStrLn(M).bind()
        val char = line.toLowerCase().first().toOption().fold(
                {
                        putStrLn(M, "Please enter a letter")
                                .flatMap { getChoice() }
                },
                { char -&amp;gt;
                        M { char }
                }
        ).bind()
        char
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;Updating all other functions follows the same pattern. Replace &lt;code&gt;IO&amp;lt;SOMETHING&amp;gt;&lt;/code&gt; with &lt;code&gt;Kind&amp;lt;F, SOMETHING&amp;gt;&lt;/code&gt;, replace &lt;code&gt;IO.binding&lt;/code&gt; with &lt;code&gt;M.binding&lt;/code&gt; and pass &lt;code&gt;M&lt;/code&gt; as parameter for reading/writing to the console.&lt;/p&gt;

&lt;p&gt;You can find the full code &lt;a href="https://gist.github.com/LordRaydenMK/0be8f70f860a862e69daf262b4a83e17"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The main program
&lt;/h2&gt;

&lt;p&gt;The main program, run with &lt;code&gt;Single&lt;/code&gt;, looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hangman(SingleK.monadDefer()).hangman.fix().single.subscribe()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;or with &lt;code&gt;IO&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hangman(IO.monadDefer()).hangman.fix().unsafeRunSync()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The decision in which type constructor to run is made at the point of execution. Switching from &lt;code&gt;Single&lt;/code&gt; to &lt;code&gt;IO&lt;/code&gt; or &lt;code&gt;Observable&lt;/code&gt; requires only updating the main function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Incremental improvements
&lt;/h2&gt;

&lt;p&gt;I am still learning FP and I don’t know most of the type-classes in Arrow and what they can do. In my first attempt I used &lt;code&gt;Async&lt;/code&gt; instead of &lt;code&gt;MonadDefer&lt;/code&gt;. &lt;code&gt;Async&lt;/code&gt; extend &lt;code&gt;MonadDefer&lt;/code&gt; and adds additional capabilities to it. I asked for feedback on the &lt;a href="https://kotlinlang.slack.com/messages/C5UPMM0A0/"&gt;#arrow&lt;/a&gt; channel and they pointed me towards &lt;code&gt;MonadDefer&lt;/code&gt;. Together with the Arrow maintainers we made a few more improvements improvements.&lt;/p&gt;

&lt;p&gt;To avoid passing &lt;code&gt;M&lt;/code&gt; to &lt;code&gt;printStrLn&lt;/code&gt; every time I can convert it to an extension function on &lt;code&gt;MonadDefer&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun &amp;lt;F&amp;gt; MonadDefer&amp;lt;F&amp;gt;.putStrLn(line: String): Kind&amp;lt;F, Unit&amp;gt; = invoke {
    println(line)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and I can use &lt;a href="https://kotlinlang.org/docs/reference/delegation.html#implementation-by-delegation"&gt;Implementation by delegation&lt;/a&gt; and have the &lt;code&gt;Hangman&lt;/code&gt; class implement &lt;code&gt;MonadDefer&amp;lt;F&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Hangman&amp;lt;F&amp;gt;(private val M: MonadDefer&amp;lt;F&amp;gt;): MonadDefer&amp;lt;F&amp;gt; by M
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This means everywhere inside the &lt;code&gt;Hangman&lt;/code&gt; class I can use the methods of &lt;code&gt;MonadDefer&lt;/code&gt; like &lt;code&gt;binding&lt;/code&gt; and &lt;code&gt;invoke&lt;/code&gt; and extension methods like &lt;code&gt;putStrLn&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val hangman: Kind&amp;lt;F, Unit&amp;gt; = binding {
        putStrLn("Welcome to purely functional hangman").bind()
        val name = getName.bind()
        putStrLn("Welcome $name. Let's begin!").bind()
        val word = chooseWord.bind()
        val state = State(name, word = word)
        renderState(state).bind()
        gameLoop(state).bind()
        Unit
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You can find the full implementation &lt;a href="https://github.com/LordRaydenMK/arrow-hangman/blob/master/src/main/kotlin/io/github/lordraydenmk/part2/Part2.kt"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Working with abstractions like &lt;code&gt;MonadDefer&lt;/code&gt; frees the business logic from implementation details like &lt;code&gt;IO&lt;/code&gt; or &lt;code&gt;Single&lt;/code&gt;. It can also enable easier composition of different modules because the decision for the concrete data type is delayed until the main program.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>functional</category>
      <category>arrowkt</category>
    </item>
    <item>
      <title>Functional Hangman in Kotlin with Arrow</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Sun, 11 Nov 2018 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/functional-hangman-in-kotlin-with-arrow-2cmd</link>
      <guid>https://dev.to/s_anastasov/functional-hangman-in-kotlin-with-arrow-2cmd</guid>
      <description>&lt;p&gt;A few days ago I run into this &lt;a href="https://abhsrivastava.github.io/2018/11/03/Hangman-Game-Using-ZIO/"&gt;blog post&lt;/a&gt; about implementing a console Hangman game using &lt;a href="https://scalaz.github.io/scalaz-zio/"&gt;Scala ZIO&lt;/a&gt;. The blog post is based on &lt;a href="https://www.youtube.com/watch?v=XONTFZ4afY0"&gt;this talk&lt;/a&gt; delivered by &lt;a href="https://twitter.com/jdegoes"&gt;John De Goes&lt;/a&gt;, for the Scala Kyiv meetup, where he codes a console Hangman game using functional programming.&lt;/p&gt;

&lt;p&gt;After I saw the post I was curious how the code would look like written in Koltin with &lt;a href="https://arrow-kt.io"&gt;arrow&lt;/a&gt; so I decided to try and write it. You can find the result &lt;a href="https://github.com/LordRaydenMK/arrow-hangman"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I am still learning functional programming so I asked for &lt;a href="https://kotlinlang.slack.com/archives/C5UPMM0A0/p1541707359083600"&gt;feedback&lt;/a&gt; from the arrow maintainers on the &lt;a href="https://kotlinlang.slack.com/"&gt;kotlinlang&lt;/a&gt; slack workspace. They were very helpful and I made a few improvements based on their feedback.&lt;/p&gt;

&lt;h1&gt;
  
  
  Key differences
&lt;/h1&gt;

&lt;p&gt;I would like to point out that the programs in Scala and Kotlin are not 100% equivalent. There are both differences in the language and the functional libraries used.&lt;/p&gt;

&lt;h2&gt;
  
  
  The IO monad
&lt;/h2&gt;

&lt;p&gt;In Scala ZIO &lt;code&gt;IO[E, A]&lt;/code&gt; describes an effect that may fail with an &lt;code&gt;E&lt;/code&gt;, run forever, or produce a single &lt;code&gt;A&lt;/code&gt;. In the Kotlin version I am using &lt;code&gt;IO&amp;lt;A&amp;gt;&lt;/code&gt; from Arrow. &lt;code&gt;IO&amp;lt;A&amp;gt;&lt;/code&gt; describes an effect that can fail with &lt;code&gt;Throwable&lt;/code&gt; or produce a single &lt;code&gt;A&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Both type classes produce an &lt;code&gt;A&lt;/code&gt;. The key difference the error. In Scala ZIO you can use any error type or even &lt;code&gt;Nothing&lt;/code&gt; to indicate the program never ends. In Arrow the &lt;code&gt;E&lt;/code&gt; type is always &lt;code&gt;Throwable&lt;/code&gt; so you don’t have to specify it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading and writing from the Console
&lt;/h2&gt;

&lt;p&gt;Scala ZIO comes with built in primitives for interacting with the &lt;a href="https://scalaz.github.io/scalaz-zio/usage/console.html"&gt;console&lt;/a&gt;. In the Kotlin version I had to implement the &lt;code&gt;readStrLn&lt;/code&gt; and &lt;code&gt;putStrLn&lt;/code&gt; functions myself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun putStrLn(line: String): IO&amp;lt;Unit&amp;gt; = IO { println(line) }

fun getStrLn(): IO&amp;lt;String&amp;gt; = IO { 
    readLine() ?: throw IOException("Failed to read input!") 
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h2&gt;
  
  
  For comprehensions
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://docs.scala-lang.org/tour/for-comprehensions.html"&gt;For comprehensions&lt;/a&gt; are built into the scala language. Unfortunately Kotlin doesn’t have the same feature. But Kotlin has &lt;a href="https://kotlinlang.org/docs/reference/coroutines-overview.html"&gt;Coroutines&lt;/a&gt; so the Arrow team built &lt;a href="https://arrow-kt.io/docs/patterns/monad_comprehensions/#comprehensions-over-coroutines"&gt;Comprehensions over coroutines&lt;/a&gt; which can be used in a similar way to make the code more readable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Scala with For comprehensions
val hangman : IO[IOException, Unit] = for {
    _ &amp;lt;- putStrLn("Welcome to purely functional hangman")
    name &amp;lt;- getName
    _ &amp;lt;- putStrLn(s"Welcome $name. Let's begin!")
    word &amp;lt;- chooseWord
    state = State(name, Set(), word)
    _ &amp;lt;- renderState(state)
    _ &amp;lt;- gameLoop(state)
} yield()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Kotlin with Arrow (Comprehensions over coroutines)
val hangman: IO&amp;lt;Unit&amp;gt; = IO.monad().binding {
    putStrLn("Welcome to purely functional hangman").bind()
    val name = getName.bind()
    putStrLn("Welcome $name. Let's begin!").bind()
    val word = chooseWord.bind()
    val state = State(name, word = word)
    renderState(state).bind()
    gameLoop(state).bind()
    Unit
}.fix()

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;Rewriting Functional Hangman from Scala to Kotlin was a nice exercise for learning FP. There are differences between Scala and Kotlin and the &lt;code&gt;IO&lt;/code&gt; type class in Scala ZIO and Arrow but the core principles are the same, we write programs by solving small problems and then combine the solutions. We use lazy evaluation and move the side effects to the edge of the system.&lt;/p&gt;

&lt;p&gt;Thanks to John who wrote this functional hangman, &lt;a href="https://twitter.com/abhishes"&gt;Abhishek&lt;/a&gt; for writing the article and &lt;a href="https://twitter.com/pacoworks"&gt;Paco&lt;/a&gt;, &lt;a href="https://twitter.com/raulraja"&gt;Raul&lt;/a&gt; and &lt;a href="https://twitter.com/mLeandroBF"&gt;Leandro&lt;/a&gt;, from the Arrow team, for the feedback about my code.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>functional</category>
      <category>arrowkt</category>
    </item>
    <item>
      <title>Setting up GitLab CI for Android Projects</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Sun, 03 Dec 2017 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/setting-up-gitlab-ci-for-android-projects-a6o</link>
      <guid>https://dev.to/s_anastasov/setting-up-gitlab-ci-for-android-projects-a6o</guid>
      <description>&lt;p&gt;My first experience with continuous integration was using Bitbucket in combination with &lt;a href="http://www.jenkins.io" rel="noopener noreferrer"&gt;Jenkins&lt;/a&gt;. I was pretty happy with my setup. Jenkins would run on every commit making sure my code compiles, run android lint and run my unit tests. I also set up continuous deployment using &lt;a href="http://www.fabric.io" rel="noopener noreferrer"&gt;Fabric&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdocs.gitlab.com%2Fee%2Fci%2Fimg%2Fcicd_pipeline_infograph.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdocs.gitlab.com%2Fee%2Fci%2Fimg%2Fcicd_pipeline_infograph.png" title="CI/CD pipeline" alt="GitLab CI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, at work, we use GitLab as a code repository. GitLab also offers &lt;a href="https://about.gitlab.com/features/gitlab-ci-cd/" rel="noopener noreferrer"&gt;continuous integration&lt;/a&gt;. When we decided to start using continuous integration at work we decided to give GitLab a chance. It was already integrated with GitLab and to use it we just needed to install a &lt;a href="https://docs.gitlab.com/runner/" rel="noopener noreferrer"&gt;runner&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using CI with GitLab is simple, after you install a runner you need to add a .gitlab-ci.yml file at the root of the repository. GitLab even offers template .gitlab-ci.yml files for various languages and frameworks. The android template is based on &lt;a href="https://about.gitlab.com/2016/11/30/setting-up-gitlab-ci-for-android-projects/" rel="noopener noreferrer"&gt;this&lt;/a&gt; blog post from 2016. It is a great guide but unfortunately today it doesn’t work. Google introduced a few changes in the command line tools.&lt;/p&gt;

&lt;h1&gt;
  
  
  Installing Android SDK
&lt;/h1&gt;

&lt;p&gt;To install the Android SDK on a CI we need to install the &lt;a href="https://developer.android.com/studio/index.html#downloads" rel="noopener noreferrer"&gt;command line tools&lt;/a&gt; (scroll to the bottom to Get just the command line tools). The command line tools include the &lt;a href="https://developer.android.com/studio/command-line/sdkmanager.html" rel="noopener noreferrer"&gt;sdkmanager&lt;/a&gt; - a command line tool that allows you to view, install, update, and uninstall packages for the Android SDK. So instead of&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- wget --quiet --output-document=android-sdk.tgz https://dl.google.com/android/android-sdk_r${ANDROID_SDK_TOOLS}-linux.tgz
  - tar --extract --gzip --file=android-sdk.tgz
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- wget --quiet --output-document=android-sdk.zip https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip
  - unzip -q android-sdk.zip -d android-sdk-linux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to download and install the Android SDK tools.&lt;/p&gt;

&lt;p&gt;There is also an improvement in accepting licenses for the Android SDK. After you accept the licenses on your development machine the tools will generate a licenses folder in the Android SDK root directory. You can transfer the licenses from your development machine to your CI server. To accept the licenses we can use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- mkdir android-sdk-linux/licenses
  - printf "8933bad161af4178b1185d1a37fbf41ea5269c55\nd56f5187479451eabf01fb78af6dfcb131a6481e" &amp;gt; android-sdk-linux/licenses/android-sdk-license
  - printf "84831b9409646a918e30573bab4c9c91346d8abd" &amp;gt; android-sdk-linux/licenses/android-sdk-preview-license
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a folder licenses with two files inside. The values written in the files are from my local machine. Depending on which components you use there might be other files on your machine like license for Google TV or Google Glass. Once the licenses are accepted we can install packages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- android-sdk-linux/tools/bin/sdkmanager --update &amp;gt; update.log
  - android-sdk-linux/tools/bin/sdkmanager "platforms;android-${ANDROID_COMPILE_SDK}" "build-tools;${ANDROID_BUILD_TOOLS}" "extras;google;m2repository" "extras;android;m2repository" &amp;gt; installPlatform.log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A sample project based on the &lt;a href="https://codelabs.developers.google.com/codelabs/android-testing/index.html" rel="noopener noreferrer"&gt;Android Testing codelab&lt;/a&gt; with the full .gitlab-ci.yaml file can be found &lt;a href="https://gitlab.com/stolea/android-gitlab-ci" rel="noopener noreferrer"&gt;here&lt;/a&gt;. The rest of the script for building and unit testing is the same as the original post. The latest x86 emulator requires hardware acceleration to run so I’ll skip the functional tests for now.&lt;/p&gt;

</description>
      <category>android</category>
      <category>ci</category>
      <category>gitlabci</category>
    </item>
    <item>
      <title>Contributing to OSS for Hacktoberfest</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Tue, 10 Oct 2017 00:00:00 +0000</pubDate>
      <link>https://dev.to/s_anastasov/contributing-to-oss-for-hacktoberfest-8c</link>
      <guid>https://dev.to/s_anastasov/contributing-to-oss-for-hacktoberfest-8c</guid>
      <description>&lt;p&gt;Digital Ocean in partnership with Github are organizing the fourth &lt;a href="https://blog.digitalocean.com/hacktoberfest-2017/"&gt;Hacktoberfest&lt;/a&gt; event this October. If you make four pull requests between October 1 and October 31 to any Github hosted repository you get a Hacktoberfest T-shirt. This year I decided to take part and I already made two pull requests.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2ntL8g-v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://assets.digitalocean.com/ghost/2017/09/Hacktoberfest17-Blog-01.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2ntL8g-v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://assets.digitalocean.com/ghost/2017/09/Hacktoberfest17-Blog-01.png" alt="hacktoberfest"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  My first OSS contribution
&lt;/h1&gt;

&lt;p&gt;I created my first pull request to an OSS project 3 years after I registered on Github. I know it can be hard to start contributing. At first I didn’t think my code was good enough, then I couldn’t find the right project with the right issue I could fix.&lt;/p&gt;

&lt;p&gt;One day an opportunity presented itself. At work I was using &lt;a href="https://github.com/frankiesardo/auto-parcel"&gt;auto-parcel&lt;/a&gt; to generate the boilerplate required for Parcebale implementation on Android. It’s a cool library based on &lt;a href="https://github.com/google/auto/tree/master/value"&gt;auto-value&lt;/a&gt; by Google. At the time I was using version 0.3 - the version displayed in the README file on Github. A few days later while creating another value class I got an error. I googled the error and it led me to an issue on the project’s Github page. The issue was closed and a new version, version 0.3.1 was released. The README file was outdated, it still pointed to the previous release containing the bug.&lt;/p&gt;

&lt;p&gt;I spent 10 minutes because of a bug that was already fixed. What a waste of time. If I wasted time chances are someone else will also run into the same problem so I decided to do something about it. Opening an issue on Github would be nice but the solution was so simple I decided to fix it myself and make a &lt;a href="https://github.com/frankiesardo/auto-parcel/pull/36"&gt;pull request&lt;/a&gt;. I also updated another dependency (android-apt) in the README to the latest version. The next day my pull request was accepted and it felt good.&lt;/p&gt;

&lt;h1&gt;
  
  
  Hacktoberfest 2017
&lt;/h1&gt;

&lt;p&gt;A few days after Hacktoberfest 2017 started I run into an interested project on Github - &lt;a href="https://github.com/edvin/tornadofx"&gt;TornadoFx&lt;/a&gt; a Lightweight JavaFX framework for Kotlin. I like Kotlin and it’s Hacktoberfest so I decided to contribute and maybe get a cool T-Shirt in the process. I noticed the project didn’t have enough unit tests so I decided to write a few. I found a file with some extension methods that were easy to test. They didn’t have tests so a wrote a few and I even found a little bug. I opened a &lt;a href="https://github.com/edvin/tornadofx/pull/486"&gt;pull request&lt;/a&gt; and my changes were merged. In my pull request I asked if more tests would be something they would be interested in. The owner replied:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for your contribution. Tests are most welcome of course :)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I also opened another pull request fixing the bug I had found.&lt;/p&gt;

&lt;p&gt;Getting started with contributing to OSS can be intimidating. Starting small can help gain some confidence. Helping with documentation or tests, like I did, is a good place to start. There are thousands of beginner friendly issues tagged with &lt;a href="https://github.com/search?utf8=%E2%9C%93&amp;amp;q=state%3Aopen+label%3Ahacktoberfest+is%3Aissue&amp;amp;type=Issues&amp;amp;utm_source=DigitalOcean_Hacktoberfest2017"&gt;hacktoberfest&lt;/a&gt; waiting for you.&lt;/p&gt;

&lt;p&gt;Are you participating in Hacktoberfest? Do you remember your first OSS contribution?&lt;/p&gt;

</description>
      <category>development</category>
      <category>opensource</category>
      <category>hacktoberfest</category>
      <category>discuss</category>
    </item>
    <item>
      <title>My First Unit Test</title>
      <dc:creator>Stojan Anastasov</dc:creator>
      <pubDate>Tue, 26 Sep 2017 19:45:02 +0000</pubDate>
      <link>https://dev.to/s_anastasov/my-first-unit-test-c44</link>
      <guid>https://dev.to/s_anastasov/my-first-unit-test-c44</guid>
      <description>&lt;p&gt;There are different reasons developers write tests. Some of them are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Validate the system&lt;/li&gt;
&lt;li&gt;Feedback&lt;/li&gt;
&lt;li&gt;To prevent regression bugs&lt;/li&gt;
&lt;li&gt;Code coverage&lt;/li&gt;
&lt;li&gt;To enable refactoring&lt;/li&gt;
&lt;li&gt;Documenting the system&lt;/li&gt;
&lt;li&gt;Orders from manager&lt;/li&gt;
&lt;li&gt;And many &lt;a href="http://www.onjava.com/pub/a/onjava/2003/04/02/javaxpckbk.html" rel="noopener noreferrer"&gt;other reasons&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are also reasons developers don't write tests like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Don't know how to write tests&lt;/li&gt;
&lt;li&gt;Writing tests is too hard&lt;/li&gt;
&lt;li&gt;Not enough time to write tests&lt;/li&gt;
&lt;li&gt;The code is too simple for tests.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the story about my first unit test written to save time.&lt;/p&gt;

&lt;h1&gt;
  
  
  The app
&lt;/h1&gt;

&lt;p&gt;I was working on a simple Android app. The app consisted of two screens, a list of items and a details screen for creating/updating/deleting items. There was also a register/login screen that are irrelevant for this story. The app worked with a remote database (on parse.com) using the REST API.  You can create an account in the app and you can CRUD some items via the API. There was a requirement for the app to work offline and sync changes with the server when it connected to the Internet.&lt;/p&gt;

&lt;p&gt;To support offline work, I created a local database to mirror the remote database. To sync the local with the remote database I used an &lt;a href="https://developer.android.com/reference/android/app/IntentService.html" rel="noopener noreferrer"&gt;IntentService&lt;/a&gt;. The IntentService was responsible for comparing the items in the two databases and determining what should be updated in the local and/or remote database. This was the most complicated part of the app.&lt;/p&gt;

&lt;h1&gt;
  
  
  Testing
&lt;/h1&gt;

&lt;p&gt;After I completed the database synchronization code I run the app on the emulator to test if it worked.&lt;/p&gt;

&lt;p&gt;Testing scenarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;New item in the local database -&amp;gt; update the remote db&lt;/li&gt;
&lt;li&gt;New item in the remote database -&amp;gt; update the local db&lt;/li&gt;
&lt;li&gt;Updated item in the local database -&amp;gt; update remote db&lt;/li&gt;
&lt;li&gt;Updated item in the remote database -&amp;gt; update local db&lt;/li&gt;
&lt;li&gt;Updated (different) item in both databases -&amp;gt; update both db&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I was doing manual testing. First I would clear the app data (to get an empty database) and clear the remote database (using the Parse website). Then I created an item in the local db, ran the sync service and checked if it appears on the remote db. The I created an item in the remote db, ran the service and checked if it appears in the local db. Then I created two new items, one in the local db, one in the remote, ran the service, checked if it's OK. Now repeat this for updating items, deleting items… It could take up to 10-15 min to test the whole synchronization logic.&lt;/p&gt;

&lt;p&gt;Of course my code didn't work the first time, it had a few bugs and I had to update my code. After a few cycles of changing two lines of code then test for 15 min I got tired. It was taking too long for me to see the effects from changing a few lines of code. There must be a better way. This boring, repetitive process was something a computer could do better.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fi.imgur.com%2FQ8kV8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fi.imgur.com%2FQ8kV8.png" title="Geeks and repetitive tasks" alt="Geeks and repetitive tasks"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Testing done right
&lt;/h1&gt;

&lt;p&gt;Fortunately Android Studio version 1.1 (and the corresponding android gradle plugin) added support for unit testing. I extracted the synchronization logic from the IntentService into a Java class responsible for comparing two lists and determining what should I update. Then I wrote some unit tests for my synchronization logic. My only Android dependency in the synchronization code was &lt;a href="https://developer.android.com/reference/android/text/TextUtils.html#isEmpty(java.lang.CharSequence)" rel="noopener noreferrer"&gt;TextUtils.isEmpty()&lt;/a&gt;. As a quick workaround I decided to copy/paste the implementation into my synchronization class. The unit tests run with JVM so no emulator. I run the tests and I got instant feedback, what had taken me 10 to 15 minutes manually was now automated down to just a few seconds. After fixing a few bugs in both the code and the tests (yeah I also wrote bugs in the tests) my app worked as expected.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fi.imgur.com%2FiEbZtl3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/http%3A%2F%2Fi.imgur.com%2FiEbZtl3.png" title="Android Studio - Unit Tests" alt="Android Studio - Unit Tests"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Writing unit tests for my synchronization logic was simple because the class had no collaborators, didn't touch the UI and had no Android dependencies[1]. Usually writing unit tests is harder, you need to design your code to be testable and it takes time to see the benefits. This low effort - high reward test made me start testing more.&lt;/p&gt;

&lt;p&gt;Do you write tests? Any interested testing stories? You can share them in the comments.&lt;/p&gt;

&lt;p&gt;[1]&lt;em&gt;except for TextUtils.isEmpty()&lt;/em&gt;&lt;/p&gt;

</description>
      <category>android</category>
      <category>testing</category>
      <category>unittests</category>
      <category>junit</category>
    </item>
  </channel>
</rss>
