HomeKotlinGetting Started with Kotlin Coroutines

Getting Started with Kotlin Coroutines

With version 1.1 of Kotlin comes a new experimental feature called coroutines. The statement means it may get some changes in the upcoming releases of Kotlin.

When compiling coroutines in Kotlin 1.1, a warning is reported by default: The feature “coroutines” is experimental. To remove the warning, you need to specify an opt-in flag.

[learn_more caption=”Opt-In Flag” state=”open”]

  • Command line: -Xcoroutines=enable
  • Gradle: kotlin { experimental { coroutines 'enable' } }
  • Maven: <configuration> <args> <arg>-Xcoroutines=enable</arg> </args> </configuration>
  • IDE: Use a quick-fix (Alt+Enter) or modify the facet options (Project Structure -> Modules -> Your Module -> Compiler -> Coroutines (experimental))

[/learn_more]

To simplify asynchronous programming, Coroutines has put the complications into libraries. The logic of the program can be expressed sequentially in a coroutine, and the underlying library will figure out the asynchrony for us. The library can wrap relevant parts of the user code into callbacks, subscribe to relevant events, schedule execution on different threads (or even different machines!), and the code remains as simple as if it was sequentially executed.

Suspending

Coroutines are computations that can be suspended without blocking a thread. No context switch or any other involvement of the OS is required. The suspension can be controlled by a user library to a large extent: as library authors, we can decide what happens upon a suspension and optimize/log/intercept according to our needs.

In the next few articles we will be covering the Kotlin Coroutines in much more depth, like, understanding coroutines suspended functions, APIs, etc.

RELATED ARTICLES

Most Popular