Kotlin Archives - CodingFlower https://www.codingflower.com/tag/kotlin Check news in the world of Senior Software Engineers! Sat, 18 Dec 2021 17:44:09 +0000 en hourly 1 How to create Mono? https://www.codingflower.com/2021/12/18/how-to-create-mono https://www.codingflower.com/2021/12/18/how-to-create-mono#respond Sat, 18 Dec 2021 17:41:33 +0000 http://www.codingflower.com/?p=1873 How to create Mono ? In this article, I would like to show you several…

The post How to create Mono? appeared first on CodingFlower.

]]>
How to create Mono ?

In this article, I would like to show you several different ways of creating reactive Mono. I'll present how to:

  • create mono without any value
  • create mono with value
  • create mono which contains an exception
  • create eager mono
  • create lazy mono
  • create mono per new subscription

but first, let's start with a short intro about Mono<T> itself.

Mono<T>

In simple words Mono<T> is a customized version of Publisher<T> which is able to emit at most one item.

Create Mono without any value

The most basic version of Mono. This Mono will complete without emitting any item.
Let's test that.

    @Test
    fun `should create empty mono`() {
        val emptyMono = Mono.empty<String>()

        StepVerifier
            .create(emptyMono)
            .expectNextCount(0)
            .verifyComplete()
    }

Create Mono with value

It would be nice to have Mono with some value inside of it, to achieve that we can use just method which accepts any type of data and returns Mono<T>. We can say that we are wrapping given data with Mono.

    @Test
    fun `should create mono with value`() {
        val createdMono = Mono.just("Mono")

        StepVerifier
            .create(createdMono)
            .expectNext("Mono")
            .verifyComplete()
    }

Create Mono which contains exception

Due to the fact that exception exists and we have to deal with them there is also a possibility to create Mono which contains an exception.

    @Test
    fun `should create error mono`() {
        val monoError = Mono.error<RuntimeException> { RuntimeException("Some fishy exception") }

        StepVerifier
            .create(monoError)
            .expectError(RuntimeException::class.java)
            .verify()
    }

Create eager Mono

What does it mean eager Mono? Basically, when we create the Mono we would like to
emit it instantly, during the creation. The method from the second paragraph will do that
for us Mono.just() emits wrapped item at the instantiation time.

    @Test
    fun `mono just is eager`() {
        val atomicInteger = AtomicInteger(0)
        val eagerMono = Mono.just(atomicInteger.incrementAndGet())

        Assertions.assertEquals(1, atomicInteger.get())
    }

Inside the Mono we are incrementing atomicInteger, but we are never subscribing
to given eagerMono, but still, incrementation takes place.

Create lazy Mono

Lazy Mono is opposite to the eager Mono, so we are not emitting anything
straight away, we are waiting for a subscription. To achieve that we can use the method
fromCallable which takes Callable as a parameter.

    @Test
    fun `mono from callable is lazy`() {
        val atomicInteger = AtomicInteger(0)
        val lazyMono = Mono.fromCallable { atomicInteger.incrementAndGet() }

        Assertions.assertEquals(0, atomicInteger.get())
    }

Inside the Mono we are incrementing atomicInteger, but we are never subscribing
to lazeMono and incrementation doesn't take a place. To execute
atomicInteger.incrementAntGet() we have to subscribe lazyMono.

Create new Mono per each subscription

Method Mono.defer() will create a provider that will deliver the given Mono for each
subscriber. Let's analyze the example below.

    @Test
    fun `mono defer` () {
        val atomicInteger = AtomicInteger(0)

        val deferedMono = Mono.defer { Mono.just(atomicInteger.incrementAndGet()) }

        StepVerifier
            .create(deferedMono)
            .expectNext(1)
            .verifyComplete()

        StepVerifier
            .create(deferedMono)
            .expectNext(2)
            .verifyComplete()
    }

We are doing two subscriptions on the same deferedMono provider. The result is quite
simple to predict, each subscription executes incrementation emitted by Mono.just()
delivered by Mono.defer() creator.

The post How to create Mono? appeared first on CodingFlower.

]]>
https://www.codingflower.com/2021/12/18/how-to-create-mono/feed 0
Kotlin Books Review from the backend developer perspective https://www.codingflower.com/2020/12/01/kotlin-books-review-from-the-backend-developer-perspective https://www.codingflower.com/2020/12/01/kotlin-books-review-from-the-backend-developer-perspective#respond Tue, 01 Dec 2020 23:35:44 +0000 http://www.codingflower.com/?p=1810 I've already read some books related to the Kotlin language so I can make a…

The post Kotlin Books Review from the backend developer perspective appeared first on CodingFlower.

]]>
I've already read some books related to the Kotlin language so I can make a short review.

Kotlin In Action

You can buy this book here.

  • For whom? For beginners, excellent for the first touch with the language.
  • When is it worth reading? At the beginning of your journey with Kotlin.

Authors: Dmitry Jemerov and Svetlana Isakova, developers on the Kotlin team.

This book was the first book that I ever read about Kotlin. The knowledge included in this book was enough to create backend services.

Effective Kotlin

You can buy this book here.

  • For whom? If you have some experience in Kotlin and you would like to know more advanced stuff.
  • When is it worth reading? From my point of view, you should read this book right after Kotlin In Action.

Author: Marcin MoskaƂa.

If you come from the Java world you probably noticed that this title is very similar to the popular book Effective Java written by Joshua Bloch. This similarity is not insignificant because Effective Kotlin has the same structure as Effective Java, but all topics describe in the book are Kotlin related instead of Java. Best-practices for Kotlin's development.

Joy Of Kotlin

You can buy this book here.

  • For whom? Advanced developers, fluent with Kotlin.
  • When is it worth reading? If you want to start functionally writing Kotlin code.

Author: Pierre-Yves Saumont

Long story short, functional programming in Kotlin, a lot of exercises and examples. I don't recommend this book if you looking for a book to start with Kotlin. To be honest the most difficult book about Kotlin that I ever read, but before reading this book I've never touch functional programming.

Learning Concurrency In Kotlin

  • For whom? Android developers, will learn some concurrency features in Kotlin.
  • When is it worth reading? If you want to use concurrency in Kotlin, but all examples are related to mobile development.

Author: Miguel Angel Castiblanco Torres

You are guided by the author through the process of creating a mobile application using coroutines and other Kotlin specific concurrency features.

Summary

  • If you java developer I recommend Kotlin In Action. After reading this book, you will be able to use Kotlin on your daily basis.
  • If you already made your hands dirty with Kotlin, I would suggest reading the Effective Kotlin, you will gain knowledge of how to write your code in a more Kotlin way.
  • If you are looking for advanced topics and functional programming choose Joy Of Kotlin but be aware that, this book is really difficult, especially if you never touch functional programming.

The post Kotlin Books Review from the backend developer perspective appeared first on CodingFlower.

]]>
https://www.codingflower.com/2020/12/01/kotlin-books-review-from-the-backend-developer-perspective/feed 0
Elasticsearch Distinct search in Spring Boot & Kotlin https://www.codingflower.com/2020/11/01/elasticsearch-distinct-search-in-spring-boot-kotlin https://www.codingflower.com/2020/11/01/elasticsearch-distinct-search-in-spring-boot-kotlin#respond Sun, 01 Nov 2020 20:18:02 +0000 http://www.codingflower.com/?p=1797 One of the most popular query in SQL world is to retrieve distinct values from…

The post Elasticsearch Distinct search in Spring Boot & Kotlin appeared first on CodingFlower.

]]>
One of the most popular query in SQL world is to retrieve distinct values from the given table. Let's leave the SQL world and dive into Elasticsearch.

We have simple document:

@Document(type = "article", indexName = "data")
data class Product(
        @Id
        val id: String? = null,
        val category: String,
        val name: String,
)

and we want to get distinct categories from Elasticsearch.

How to do that?

Using Elasticsearch dev tools we can prototype query which returns us categories:

GET data/_search
{
  "size": 0, 
     "aggs":{
        "distinctCategory": {
            "terms": {
                "field": "category.keyword"
                , "size": 100
            }
        }
    }
}

We have to make aggregation distinctCategory on this index by category field. We have to change size value inside aggregation to more than the default (10) because we are expecting our index has more than 10 different categories.

We are setting size to 0 because we don't need any result from the data index, we care about aggregation.

Response for this query looks like:

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
      ...
  },
  "hits" : {
      ...
  },
  "aggregations" : {
    "distinctCategory" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "road bikes",
          "doc_count" : 2130
        },
        {
          "key" : "gravel bikes",
          "doc_count" : 1916
        },
        {
          "key" : "bmx",
          "doc_count" : 1763
        }
      ]
    }
  }
}

The most important part of the response for us is aggregations. Field buckets contains our information.

How to make Elasticsearch a distinct query in Kotlin?

First we need to create aggregation, we are lucky because Elasticsearch create bunch of useful builders.

val aggregation = AggregationBuilders.terms("distinctCategory")
                .field("category.keyword")
                .size(100)

After that we only need to attach our aggregation to the search query:

val searchSourceBuilder = SearchSourceBuilder().size(0).aggregation(aggregation)
        val searchRequest = SearchRequest("data")
                .apply { source(searchSourceBuilder) }

To execute query:

val searchResponse = esConfiguration.client().search(searchRequest, RequestOptions.DEFAULT)

esConfiguration.client() returns RestHighLevelClient.

Our query works, but how to extract the distinct values?

It is very simple, as you can notice in JSON response, distinct categories names are placed in buckets list as keys.

val distincCategories = searchResponse.aggregations
    .get<Terms>("distinctCategory")
    .buckets.map { it.keyAsString }
    .toList()

The post Elasticsearch Distinct search in Spring Boot & Kotlin appeared first on CodingFlower.

]]>
https://www.codingflower.com/2020/11/01/elasticsearch-distinct-search-in-spring-boot-kotlin/feed 0