Reader small image

You're reading from  Kotlin Design Patterns and Best Practices - Second Edition

Product typeBook
Published inJan 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801815727
Edition2nd Edition
Languages
Right arrow
Author (1)
Alexey Soshin
Alexey Soshin
author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin

Right arrow

Chapter 7: Controlling the Data Flow

The previous chapter covered an important Kotlin concurrency primitive: coroutines. In this chapter, we'll discuss two other vital concurrent primitives in Kotlin: channels and flows. We'll also touch on higher-order functions for collections, as their API is very similar to that of channels and flows.

The idea of making extensive use of small, reusable, and composable functions comes directly from the functional programming paradigm, which we discussed in the previous chapter. These functions allow us to write code in a manner that describes what we want to do instead of how we want to do it.

In this chapter, we'll cover the following topics:

  • Reactive principles
  • Higher-order functions for collections
  • Concurrent data structures
  • Sequences
  • Channels
  • Flows

After reading this chapter, you'll be able to efficiently communicate between different coroutines and process your data with ease.

...

Technical requirements

In addition to the technical requirements from the previous chapters, you will also need a Gradle-enabled Kotlin project to be able to add the required dependencies.

You can find the source code used in this chapter on GitHub at the following location:

https://github.com/PacktPublishing/Kotlin-Design-Patterns-and-Best-Practices/tree/main/Chapter07

Reactive principles

We'll start this chapter with a brief detour into Reactive programming, as it forms the foundation of the data streaming concept.

Reactive programming is a paradigm based on functional programming in which we model our logic as a set of operations in a data stream. The fundamental concepts of reactive programming are summarized nicely in The Reactive Manifesto (https://www.reactivemanifesto.org).

According to this manifesto, reactive programs should be all of the following:

  • Responsive
  • Resilient
  • Elastic
  • Message-driven

To understand these four principles, we'll use an example.

Let's imagine you are calling your Internet Service Provider, since your internet is slow, for example. Do you have this picture in your mind? Let's start then.

Responsive principle

How much time are you willing to spend waiting on the line? That depends on the urgency of the situation and how much time you have. If you're in...

Higher-order functions on collections

We briefly touched on this topic in Chapter 1, Getting Started with Kotlin, but before we can discuss streams, let's make sure that those of us who come from languages that don't have higher-order functions on collections know what they are, what they do, and what the benefits of using them are.

We won't be able to cover all of the functions available on collections, but we'll cover the most widely used ones.

Mapping elements

The map() function takes each element of a collection and returns a new element of a possibly different type. To understand this idea better, let's say we have a list of letters and we would like to output their ASCII values.

First, let's implement it in an imperative way:

val letters = 'a'..'z'
val ascii = mutableListOf<Int>()
for (l in letters) {
    ascii.add(l.toInt())
}

Notice that even for such a trivial task, we had to write...

Exploring concurrent data structures

Now we're familiar with some of the most common higher-order functions on collections, let's combine this knowledge with what we learned in the previous chapter about concurrency primitives in Kotlin to discuss the concurrent data structures Kotlin provides.

The two most essential concurrent data structures are channels and flows. However, before we can discuss them, we need to look at another data structure: sequences. While this data structure is not concurrent itself, it will provide us with a bridge into the concurrent world.

Sequences

Higher-order functions on collections existed in many functional programming languages for a long time. But for Java developers, the higher-order functions for collections first appeared in Java 8 with the introduction of the Stream API.

Despite providing developers with valuable functions such as map(), filter(), and some of the others we already discussed, there were two major drawbacks...

Summary

This chapter was dedicated to practicing functional programming with reactive principles and learning the building blocks of functional programming in Kotlin. We also learned about the main benefits of reactive systems. For example, such systems should be responsive, resilient, elastic, and driven by messaging.

Now, you should know how to transform your data, filter your collections, and find elements within the collection that meet your criteria.

You should also better understand the difference between cold and hot streams. A cold stream, such as a flow, starts working only when someone subscribes to it. A new subscriber will usually receive all of the events. On the other hand, a hot stream, such as a channel, continuously emits events, even if nobody is listening to them. A new subscriber will receive only the events that were sent after the subscription was made.

We also discussed the concept of backpressure, which can be implemented in a flow. For example, if...

Questions

  1. What is the difference between higher-order functions on collections and on concurrent data structures?
  2. What is the difference between cold and hot streams of data?
  3. When should a conflated channel or flow be used?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Second Edition
Published in: Jan 2022Publisher: PacktISBN-13: 9781801815727
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin