Kotlin Standard Library Cookbook
eBook - ePub

Kotlin Standard Library Cookbook

Master the powerful Kotlin standard library through practical code examples

  1. 242 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Kotlin Standard Library Cookbook

Master the powerful Kotlin standard library through practical code examples

About this book

Build optimized applications in Kotlin by learning how to make use of the standard library features the smart way

Key Features

  • Get the most out of the Kotlin library to develop high-quality portable applications
  • Explore the powerful support for data processing and I/O operations
  • Discover ways to enhance your Android application development

Book Description

Given the verbosity of Java, developers have turned to Kotlin for effective software development. The Kotlin standard library provides vital tools that make day-to-day Kotlin programming easier. This library features the core attributes of the language, such as algorithmic problems, design patterns, data processing, and working with files and data streams.

The recipes in this book offer coding solutions that can be readily executed. The book covers various topics related to data processing, I/O operations, and collections transformation. We'll walk through effective design patterns in Kotlin and you'll understand how coroutines add new features to JavaScript.

As you make your way through the chapters, you'll learn how to implement clean, reusable functions and scalable interfaces containing default implementations. In the concluding chapters, we'll provide recipes on functional programming concepts, such as lambdas, monads, functors, and Kotlin scoping functions.

By the end of the book, you'll be able to address a range of problems that Kotlin developers face by implementing easy-to-follow solutions.

What you will learn

  • Work with ranges, progressions, and sequences in use cases
  • Add new functionalities to current classes with Kotlin extensions
  • Understand elements such as lambdas, closures, and monads
  • Build a REST API consumer with Retrofit and a coroutine adapter
  • Discover useful tips and solutions for making your Android projects
  • Explore the benefits of standard library features

Who this book is for

This book is for software developers who are familiar with Kotlin's basics and want to discover more advanced features and concepts, especially those provided by the Kotlin standard library. It's also ideal for experienced software developers who are familiar with the functional programming paradigm and other programming languages who want to switch to Kotlin. It will also help Java developers switch to Kotlin and integrate it into existing Java Virtual Machine (JVM) projects.

Trusted by 375,005 students

Access to over 1 million titles for a fair monthly price.

Study more efficiently using our study tools.

Making Asynchronous Programming Great Again

In this chapter, we will cover the following recipes:
  • Executing tasks in the background using threads
  • Background threads synchronization
  • Using coroutines for asynchronous, concurrent execution of tasks
  • Using coroutines for asynchronous, concurrent tasks execution with results handling
  • Applying coroutines for asynchronous data processing
  • Easy coroutine cancelation
  • Building a REST API client with Retrofit and a coroutines adapter
  • Wrapping third-party callback-style APIs with coroutines

Introduction

This chapter is going to address various aspects of asynchronous programming problems. The first two recipes, Executing tasks in the background using threads and Background-threads synchronization, are going to explain the standard library support for running background tasks using JVM threads.
In the further recipes, we are going to delve more deeply into the powerful Kotlin Coroutines framework. Those recipes are going to explain a general usage of coroutines for asynchronous and concurrent tasks executing. They will also present how to employ coroutines for solving more specific daily-life programming problems, such as concurrent data processing, asynchronous REST-call handling, and working with third-party callback-style APIs in a clean way. After reading this chapter, you will feel convenient applying the coroutines framework to write robust asynchronous code or to optimize your code by running expensive computations concurrently.
The Kotlin Coroutines framework is not only a handy replacement for platform-specific concurrency and async frameworks. Its power is based on providing a unified, universal API that allows us to write asynchronous code, which can be run both on JVM, Android, JavaScript, and native platforms.

Executing tasks in the background using threads

In this recipe, we are going to explore how to work effectively with the JVM Thread class in a clean way using the Kotlin standard library functions dedicated to convenient thread-running. We are going to simulate two long-running tasks and execute them concurrently in background threads.

Getting ready

In this recipe, we are going to make use of two functions simulating long-running operations. Here is the first:
private fun `5 sec long task`() = Thread.sleep(5000)
And here is the second:
private fun `2 sec long task`() = Thread.sleep(2000)
They are both just responsible for blocking a current thread for five and two seconds, respectively, in order to simulate long-running tasks. We will also make use of the predefined function returning the current thread name for debugging purposes:
private fun getCurrentThreadName(): String = Thread.currentThread().name

How to do it...

  1. Let's start by logging the current thread name to the console:
println("Running on ${getCurrentThreadName()}")
  1. Start a new Thread and invoke the `5 sec long task`() function inside it:
println("Running on ${getCurrentThreadName()}")

thread {
println("Starting async operation on ${getCurrentThreadName()}")

`5 sec long task`()
println("Ending async operation on ${getCurrentThreadName()}")
}
  1. Start another Thread and invoke `2 sec long task`() inside it:
println("Running on ${getCurrentThreadName()}")

thread {
println("Starting async operation on ${getCurrentThreadName()}")
`5 sec long task`()
println("Ending async operation on ${getCurrentThreadName()}")
}

thread {
println("Starting async operation on ${getCurrentThreadName()}")

`2 sec long task`()
println("Ending async operation on ${getCurrentThreadName()}")
}

How it works...

The preceding code is going to print the following text to the console:
Running on main
Starting async operation on Thread-0
Starting async operation on Thread-1
Ending async operation on Thread-1
Ending async operation on Thread-0
As you can see, we have successfully started two background threads, which are running concurrently. We are using the thread() utility function from the kotlin.concurrent package, w...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Ranges, Progressions, and Sequences
  8. Expressive Functions and Adjustable Interfaces
  9. Shaping Code with Kotlin Functional Programming Features
  10. Powerful Data Processing
  11. Tasteful Design Patterns Adopting Kotlin Concepts
  12. Friendly I/O Operations
  13. Making Asynchronous Programming Great Again
  14. Best Practices for the Android, JUnit, and JVM UI Frameworks
  15. Miscellaneous
  16. Other Books You May Enjoy

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access Kotlin Standard Library Cookbook by Samuel Urbanowicz in PDF and/or ePUB format, as well as other popular books in Computer Science & Object Oriented Programming. We have over one million books available in our catalogue for you to explore.