Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How Kotlin's coroutines improve code readability

December 3, 2018
Faisal Masood
Related topics:
Java

Share:

    Programs must be written for people to read, and only incidentally for machines to execute. — Abelson and Sussman

    Kotlin is a new practical language designed to solve real-world problems. It is based on JVM but there are many differences between Kotlin and Java. Kotlin is a null-safe and concise language with support for functional programming. You can try programming in Kotlin here.

    Kotlin coroutines provide an easy way to write highly scalable code, using the traditional style of programming, while avoiding having a thread allocated to each task.

    In this article, I focus on code readability and how, in my opinion, coroutines provide a cleaner approach to writing code compared to a reactive approach. I have used Project Reactor to showcase the reactive code; however, the example can be extended to any reactive library, for example, RxJava and CompleteableFuture. Note that coroutine-based code scales as well as code written using a reactive approach. To me, coroutines are a win-win situation for developers.

    You can read more about Kotlin coroutines here. The very exciting Project Loom is going to bring the lightweight thread model to Java. It is a similar concept as GOLang routines.

    Approach

    I have implemented the following workflow using both Reactor and the coroutines approach. The main function is processOrder, which performs the following:

    • The process starts with concurrent calls to getOrderInfo and getShipmentInfo, in parallel.
    • Upon completion of both the methods mentioned above, the process calls the sendEmail method.

    Let's call the processOrder function the process function and let's call the individual getOrderInfo, getShipmentInfo, and sendEmail functions business functions. This code is available in this repo. It showcases how Kotlin couroutines can be used to write more-readable code compared to a reactive approach without losing the scalability benefits.

    Simple is beautiful

    In this section, you can find code that implements the getOrderInfo and getShipmentInfo business functions and the processOrder process function using Kotlin's coroutines and also using a reactive approach.

    Business Functions

    Following are examples of the business functions using Kotlin's approach. Note that these functions are just representing the business logic with much less non-functional overhead:

    fun getOrderInfo(orderId: String): String {
         return "Order Info $orderId"
    }
    fun getShipmentInfo(orderId: String): String {
         return "Shipped for order $orderId"
    }

    Note that the same functions when written in Kotlin, mix the non-functional aspects of the code with the business logic.

    Mono<String> getOrderInfo(String orderId) {
         return Mono.just("Order Info " + orderId);
    }
    Mono<String> getShipmentInfo(StringorderId) {
         return Mono.just("Shipped for order "+ orderId);
    }

    Process Function

    In this section, you can find code that implements the processOrder process function using Kotlin's coroutines and a reactive approach. Note that by using Kotlin's approach, the code is highly readable. The code documents itself for what the business function is trying to do.

    fun processOrder() = runBlocking {
      val orderId = "SN19876"
      val orderInfo = async { getOrderInfo(orderId) }
      val shipmentInfo = async { getShipmentInfo(orderId) }
      sendEmail(shipmentInfo.await(), orderInfo.await())
    }

    The snippet below shows the same business process implemented using the reactive approach. The code below is less readable because the non-functional aspects of the code are present with the functional aspects of the business process.

    void processOrder() {
      String orderIdNumber = "SN19876";
    
      Mono.zip(getOrderInfo(orderIdNumber), getShipmentInfo(orderIdNumber))
          .flatMap(data -> sendEmail(data.getT1(), data.getT2()))
          .doOnSuccess(o -> System.out.println("Email sent " + o))
          .subscribe();
    }

    Conclusion

    From the examples above, it is evident that coroutines provide a better alternative for writing more-readable code. The reactive code referenced in this blog can be optimized to reduce more noise, but there will always be non-functional aspects of the code being mixed with the business aspect, which I can avoid now using Kotlin's coroutines.

    Kotlin is an exciting new programming language, especially if you are coming from a Java background. You can start your Kotlin journey by attending this coursera course.

    In addition, you might find this article interesting: Inter-Reactive Kotlin Applications.

    Last updated: December 9, 2018

    Recent Posts

    • GuideLLM: Evaluate LLM deployments for real-world inference

    • Unleashing multimodal magic with RamaLama

    • Integrate Red Hat AI Inference Server & LangChain in agentic workflows

    • Streamline multi-cloud operations with Ansible and ServiceNow

    • Automate dynamic application security testing with RapiDAST

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue