<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ralf Stuckert on Medium]]></title>
        <description><![CDATA[Stories by Ralf Stuckert on Medium]]></description>
        <link>https://medium.com/@ralf.stuckert?source=rss-52a2783859a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aLtmduFoMqZeVjApayxZTw.jpeg</url>
            <title>Stories by Ralf Stuckert on Medium</title>
            <link>https://medium.com/@ralf.stuckert?source=rss-52a2783859a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:35:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ralf.stuckert/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin Companion Extensions and Blocks]]></title>
            <link>https://medium.com/@ralf.stuckert/kotlin-companion-extensions-and-blocks-93484fd5a76b?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/93484fd5a76b</guid>
            <category><![CDATA[kotlin-extension-function]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-features]]></category>
            <category><![CDATA[companion-object]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 04:59:35 GMT</pubDate>
            <atom:updated>2026-10-14T10:58:08.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e3mQfdZHjKPZdIt_9BRUA.png" /></figure><blockquote>Companion objects have been Kotlin’s answer to static members since 1.0. With Kotlin 2.5.0, <a href="https://github.com/Kotlin/KEEP/blob/main/proposals/KEEP-0449-companions-block-extension.md">KEEP-0449</a> introduces two new experimental features — companion blocks and companion extensions — that finally decouple “accessible through the type name” from “there is an object behind it”. After a recap of why the companion object was not quite enough, this article walks through the syntax and the use cases.</blockquote><p>- <a href="#7fc6">Companion Objects</a><br>- <a href="#ab92">So What’s Missing</a><br>- <a href="#12d5">Companion Extensions</a><br>- <a href="#6311">Companion Blocks</a><br>- <a href="#338d">Use Cases</a><br> — <a href="#7cac">Extending Types You Don’t Own</a><br> — <a href="#af65">Extension Properties With a Backing Field</a><br> — <a href="#ebfd">Statics Without @JvmStatic</a><br> — <a href="#b2c0">Constructor-like Factories: invoke() and of()</a><br>- <a href="#a9be">Resolution and Limitations</a><br>- <a href="#8e61">Conclusion</a></p><h3>Companion Objects</h3><p>Kotlin has no static keyword. Everything that in Java would be a class member goes into a companion object instead. Say some UI library gives us a Color:</p><pre>class Color(val rgb: Int) {<br>    companion object {<br>        val Black = Color(0x000000)<br><br>        fun fromHex(hex: String) = Color(hex.removePrefix(&quot;#&quot;).toInt(16))<br>    }<br>}</pre><p>The companion object is an ordinary object — it can implement interfaces, it can be passed around as a value, it has a name — with one piece of magic on top: its members are reachable through the name of the <em>type</em>. We can write Color.Black and Color.fromHex(&quot;#6750A4&quot;) instead of Color.Companion.Black.</p><p>Now our app has brand colors. They have no business in a general-purpose UI library, but we would very much like to reach them the same way we reach Black. And because the companion is an ordinary object, we can simply write an extension for it:</p><pre>val Color.Companion.BrandPrimary get() = Color(0x6750A4)<br><br>val header = Color.BrandPrimary</pre><p>BrandPrimary lives in our own file, far away from the library, and is still reachable through the type name exactly like Black is. But let’s see what the compiler actually produces for Color.Black:</p><pre>Color.Companion.getBlack()</pre><p>So after all it is just syntactic sugar. Color.Black looks like a static function but is just a shorcut for accessing the companions object member. That observation is the key to this whole article. A companion object bundles two quite different things: <em>being reachable through the type name</em>, and <em>being an object</em>. Everything KEEP-0449 does comes from pulling those two apart.</p><h3>So What’s Missing</h3><p>Two things, as it turns out. Extending the companion object only worked because there <em>was</em> one. companion object is an ordinary class, and you cannot write an extension for a class that does not exist — so if the author of Color had not written those two words, Color.BrandPrimary would be out of reach, and we had to introduce some kind of ColorUtils object. Whether a type can be extended on type level is decided by its author, usually without a thought, and the decision is final for everybody else.</p><p>This is an old complaint. <a href="https://youtrack.jetbrains.com/issue/KT-11968">KT-11968</a> — <em>“Research and prototype namespace-based solution for statics and static extensions”</em> — was filed in April 2016, and the KEEP still cites it as one of the issues it closes.</p><p>And where it does work, what you get is thinner than it looks. BrandPrimary is at last the same as a regular extension property, which means it is a static getter taking the companion as a receiver. There is no field anywhere to put a value in, which is why an extension property may only ever have a get().</p><pre>public static final Color getBrandPrimary(Color$Companion $this$BrandPrimary);</pre><p>The second is that even the types we <em>can</em> extend are not in great shape. Here is what Color actually compiles to:</p><pre>public final class Color {<br>  public static final Color$Companion Companion;   // a field, always initialized<br>  private static final Color Black;<br>  public static final Color access$getBlack$cp();  // plus a synthetic accessor<br>  static {};<br>}</pre><p>Plus a second class file, Color$Companion.class, for a companion holding one constant. Every type with a companion object pays for an extra class to load and an object to allocate, touched or not — irrelevant for one Color, and worse on Kotlin/Native, where each access may have to check whether that instance exists yet.</p><p>And after all that we still do not have a static. Where something outside Kotlin insists on a real one, we have to ask for it by hand. JUnit 4, for instance, requires @BeforeClass to be public static void:</p><pre>class Tests {<br>    companion object {<br>        @BeforeClass     // forget @JvmStatic ...<br>        fun setUpClass() { database = connect() }<br>    }<br>}</pre><p>We forgot about the @JvmStatic, and nothing will tell you. It compiles, the test runs, the fixture is never set up, and gives you a UninitializedPropertyAccessException. And for multiplatform projects things get even more complicated: you have to remember a different annotation for every target in a multiplatform library — @JvmStatic, @JsStatic, and so on.</p><p>So the real complaint is that companion object is doing two jobs at once. It is the only way to say <em>&quot;reachable through the type name&quot;</em>, and it is also — unavoidably — an object with a class, an instance and an initialization order attached. The five problems the KEEP lists split cleanly along that seam: one language problem (no companion, no extension) and four codegen problems (@JvmStatic, one annotation per platform, the allocation, and no expect/actual matching against platform statics).</p><p>Which is why the solution comes in two parts.</p><h3>Companion Extensions</h3><p>Let’s say we have to deal with an existing class User that is not in our hands, and it has no companion object:</p><pre>data class User(val name: String)</pre><p>With the new feature you can write companion extension properties and functions:</p><pre>companion val User.Anonymous: User get() = User(&quot;Anonymous&quot;)<br><br>companion fun User.describe(): String {<br>    // no `this` here - no value receiver, and no User.Companion either<br>    return &quot;User instances have a name&quot;<br>}</pre><p>User has no companion object here, and it does not need one. As a result, there is no receiver, neither as a parameter nor as a this. That is worth sitting with for a second. The receiver in a companion extension is not a value you receive; it is a statement about <em>where the function may be found</em>. We will see this again in the generated code later, where it disappears entirely.</p><p>Mutable and constant properties work as well:</p><pre>companion var User.defaultName: String = &quot;Anonymous&quot;<br><br>const companion val User.MAX_NAME_LENGTH: Int = 100</pre><p>There is one notable restriction: companion extensions may only be declared at <strong>top level</strong>. The reason is resolution — allowing them in arbitrary nested scopes would make the rules considerably harder to pin down. In the days before <a href="https://medium.com/@ralf.stuckert/kotlin-context-parameters-0156f2911462">context parameters</a> that would have been a painful limitation. Today it is much less so: if such a function needs additional scope, it can simply ask for it with a context parameter.</p><p>Take the Color from the introduction, whose brand colour in any real application depends on the active theme. Being top level, companion val Color.BrandPrimary: Color get() = Color(0x6750A4) is one fixed colour, for everybody who imports it — there is no scope it could read a theme from. Unless we ask for one:</p><pre>context(theme: Theme)<br>companion val Color.BrandPrimary: Color get() = Color(theme.primary)<br><br>...<br>context(LightTheme) { Color.BrandPrimary }   // #6750A4<br>context(DarkTheme) { Color.BrandPrimary }    // #D0BCFF</pre><h3>Companion Blocks</h3><p>Companion extensions are written from the outside, by people who do <em>not</em> own the type. They answer the first of our two problems: the one where a companion object is missing and we cannot add one.</p><p>They do nothing about the second: the allocation, the extra class file, the @JvmStatic dance — all of that belongs to the author of the type, and no amount of extending from outside will fix it. That is what companion blocks are for. Here is the author of our Color library, before and after:</p><pre>class Color(val rgb: Int) {<br>    companion object {              //  &lt;- today<br>        val Black = Color(0x000000)<br>    }<br>}</pre><pre>class Color(val rgb: Int) {<br>    companion {                     //  &lt;- new<br>        val Black = Color(0x000000)<br>    }<br>}</pre><p>One word shorter, and that word is the whole point. A companion block keeps the <em>companion</em> part and drops the <em>object</em> part. Its members are reachable through the type name and take part in context-sensitive resolution, just as before — but there is no classifier and no instance behind them. You see the difference the moment you try to treat the companion as a thing:</p><pre>println(Color.Companion)    // does not compile: there is no such classifier<br>val c: Any = Color          // does not compile: a type name is not an expression</pre><p>With a companion object, both of those are legal. With a companion block they are not, and that is by design. If you need an object — to implement an interface, to pass around, to use as a receiver — then a companion object is still the right tool, and it is not going anywhere. What does still work is the convenience you expect from a class member:</p><pre>class Color(val rgb: Int) {<br>    companion {<br>        val Black = Color(0x000000)<br>    }<br><br>    fun isBlack(): Boolean = rgb == Black.rgb   // unqualified, from inside the class<br>}</pre><p>Only function and property declarations are allowed in a companion block. In particular there is no init block — deliberately, since class initialization is hard enough to reason about without a general-purpose hook in it.</p><p>It is worth being precise about what a companion block buys you, because it is <em>not</em> expressiveness: anything you can put in a block you could have put in a companion object. What changes is what the compiler emits — and that is the whole point, since four of the five problems were about generated code. So the two features look alike at the call site and are not interchangeable at all:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d3afc202c564dc577992542bbdf862/href">https://medium.com/media/72d3afc202c564dc577992542bbdf862/href</a></iframe><h3>Use Cases</h3><h4>Extending Types You Don’t Own</h4><p>German dates are written 01.10.2026, and LocalDate.parse() does not accept that, so a LocalDate.fromGerman() would be genuinely useful. But LocalDate is a plain Java class with no companion class behind it to extend, so for a decade the answer has been a DateUtils object holding a function that everybody can see belongs on LocalDate. But with companion extension functions this becomes quite natural:</p><pre>companion fun LocalDate.fromGerman(value: String) = LocalDate.parse(value, germanFormatter)<br><br>companion fun UUID.zero() = UUID(0L, 0L)<br><br>companion fun File.temp(name: String) = File(System.getProperty(&quot;java.io.tmpdir&quot;), name)</pre><p>The statics that are already on the type keep working, and keep their priority:</p><pre>LocalDate.of(2026, 10, 1)           // still the Java static<br>LocalDate.fromGerman(&quot;01.10.2026&quot;)  // yours</pre><p>So please: delete the DateUtils object ;-)</p><h4>Extension Properties With a Backing Field</h4><p>This one is about a restriction that is lifted <em>for a reason</em>, and the reason tells you a lot about what a companion extension really is. You might have run into this eventually:</p><pre>val Config.derived: String get() = &quot;derived from $name&quot;  // recomputed on every access<br><br>val Config.cached: String = compute()                    // error: cannot be initialized</pre><p>The reason is the one from section 2: an extension property is a static getter taking the receiver as a parameter, and a getter has nowhere to keep anything. A companion extension property is a different species. Its receiver is the <em>type</em>, and there is exactly one of those — so there is no “which instance owns this field?” to answer, and the KEEP grants an exemption: an initializer, and with it a backing field.</p><pre>companion val Config.defaults: List&lt;String&gt; = loadDefaults()  // runs once<br><br>companion var Config.activeProfile: String = &quot;dev&quot;  // mutable type-level state</pre><p>The generated code shows where that field lives — and what is missing from it:</p><pre>private static final List defaults;       // a private static of the file class<br><br>public static final List getDefaults();    // no receiver parameter!<br><br>static { defaults = loadDefaults(); }</pre><p>A regular extension would have been getDerived(Config $this$derived). A companion extension has no receiver to pass, so the type is erased from the signature entirely — it only ever told the compiler under which name you may call this. Inside a companion block it works the same, except that the field belongs to the class itself, and const val is initialized before everything else.</p><p>And the obvious warning: companion var is global mutable state. The feature lifts a technical restriction, it does not improve weird design.</p><h4>Statics Without @JvmStatic</h4><pre>class LegacyParser private constructor(val source: String) {<br>    companion object {<br>        @JvmStatic fun parse(source: String) = LegacyParser(source)<br>        val DEFAULT: LegacyParser = LegacyParser(&quot;&quot;)<br>    }<br>}<br><br>class Parser private constructor(val source: String) {<br>    companion {<br>        fun parse(source: String) = Parser(source)<br>        val DEFAULT: Parser = Parser(&quot;&quot;)<br>    }<br>}</pre><p>Same call site, Parser.parse(&quot;x&quot;), either way. The difference only shows up underneath:</p><pre>public final class LegacyParser {<br>  public static final LegacyParser$Companion Companion;   // allocated, always<br>  public static final LegacyParser parse(java.lang.String);<br>  public static final LegacyParser access$getDEFAULT$cp();<br>}<br><br>public final class Parser {<br>  public static final Parser parse(java.lang.String);<br>  public static final Parser getDEFAULT();<br>}</pre><p>Everything section 2 complained about is simply absent: no Parser$Companion class file, no Companion field to initialize, no synthetic accessor, no annotation to remember. Which also disarms the JUnit trap — @BeforeClass needs no @JvmStatic, because there is nothing non-static left to opt out of:</p><pre>class JUnitStaticTest {<br>    companion {<br>        lateinit var database: String<br><br>        @BeforeClass <br>        fun setUpClass() { database = &quot;in-memory-db&quot; }<br>    }<br>}</pre><p>Static by construction, so the annotation alone is enough. The same property holds across (multi-)platforms, which takes care of problems #3 and #5: an expect class with a companion block needs no @JvmStatic or @JsStatic anywhere, and on the JVM you can even write actual typealias Timeout = java.time.Duration and let a <em>Java</em> static actualize a companion block member.</p><h4>Constructor-like Factories: invoke() and of()</h4><p>Operators are forbidden in companion blocks, since a type name is not a value, e.g. something like Money + 1 must never become legal. There are exactly two exceptions, the invoke operator:</p><pre>class Money private constructor(val cents: Long) {<br>    companion {<br>        operator fun invoke(euros: Long) = Money(euros * 100)<br>    }<br>}<br><br>Money(5)   // 5.00 EUR - no public constructor in sight</pre><p>so you can setup constructor like functions, even for Java types using companition extensions :-)</p><p>And the of operator:</p><pre>class Tags private constructor(val values: List&lt;String&gt;) {<br>    companion {<br>        operator fun of(vararg values: String) = Tags(values.toList())<br>    }<br>}<br><br>val tags: Tags = [&quot;kotlin&quot;, &quot;keep&quot;]   // Tags[kotlin, keep]</pre><p>of is what collection literals desugar to, behind -Xcollection-literals. One asymmetry worth half a sentence: as already said, invoke may also be a companion extension, so you can bolt a constructor-like factory onto a foreign type, while of may not.</p><h3>Resolution and Limitations</h3><p>What happens when a type has both? The rule is short:</p><pre>class Example {<br>    companion object {<br>        fun foo() = 1<br>    }<br>}<br><br>companion fun Example.foo() = 2<br><br>Example.foo()   // 2</pre><p>T.foo() is resolved against companion blocks and extensions first, and only then as T.Companion.foo(). Blocks and extensions form their own receiver, which is exhausted before the companion object is consulted. If you need the other one, say so explicitly: Example.Companion.foo().</p><p>The rest of the limitations, briefly:</p><ul><li>Companion extensions are <strong>top-level only</strong>.</li><li>The receiver must be a plain classifier: no type parameters, no type arguments, no objects.</li><li>No init in a companion block; only functions and properties.</li><li>No classifier means no interface implementation and no passing it as a value — still a job for companion object.</li><li>On the JVM, a static and an instance method may not share a signature. Use @JvmName if they clash.</li></ul><h3>Conclusion</h3><p>Two features, two different problems. <strong>Companion extensions</strong> remove a restriction that should never have been there: you can now add type-level functions and properties to any type, including ones from Java, without the original author having had the foresight to write a companion object. <strong>Companion blocks</strong> change what the compiler produces: real statics on the platforms that have them, no nested class, no singleton, no annotation per platform.</p><p>What they do not do is replace companion objects. The moment you need the companion to <em>be</em> something — an interface implementation, a value you pass around, a receiver, or something a framework can reflect over — you need an object, and companion object remains exactly the right tool. The rule of thumb I would suggest: keep companion object where it is part of your public API, and reach for companion { } in new code where it was only ever standing in for static.</p><p>Ten years after KT-11968 was filed, it can probably be closed.</p><blockquote>“Punching your companions is unhelpful. <br>Go into the forest and practice unarmed combat against a tree.”<br><strong><em>Jeff Mach — There and Never, Ever Back Again</em></strong></blockquote><p><em>You will find the the source code and some more examples in the accompanying </em><a href="https://github.com/ralfstuckert/kotlin-companion-extensions"><em>Github repository</em></a><em>. The proposal itself is </em><a href="https://github.com/Kotlin/KEEP/blob/main/proposals/KEEP-0449-companions-block-extension.md"><em>KEEP-0449</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93484fd5a76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Context Parameters]]></title>
            <link>https://medium.com/@ralf.stuckert/kotlin-context-parameters-0156f2911462?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0156f2911462</guid>
            <category><![CDATA[extension-functions]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <category><![CDATA[kotlin-features]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 07:06:16 GMT</pubDate>
            <atom:updated>2026-02-24T05:13:43.208Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Context receivers have been around in Kotlin since version 1.6.20 in experimental state, now they have entered preview state with version 2.2.0 under the name context parameters. The experimental phase has been used to get a better understanding of the use cases, to introduce improvements and to clarify the syntax. After a recap of the evolution, this article will show some use cases and the syntax, in order to give you an impression of the possibilities offered by context parameters.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VfyqaPPisNBCH_H7" /><figcaption>Photo by <a href="https://unsplash.com/@valleyman?utm_source=medium&amp;utm_medium=referral">Pat Farrell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>- <a href="#8020">Extension Functions</a><br>- <a href="#b8d6">Multiple Receivers</a><br>- <a href="#781a">Context Parameters</a><br>- <a href="#e179">Use Cases</a><br> — <a href="#5afa">Depencency Injection / Implicit Services</a><br> — <a href="#cc6b">Scoped Functions</a><br> — <a href="#9797">Externally implemented Interfaces / Type Classes</a><br> — <a href="#d5db">DSLs</a><br>- <a href="#d2e6">Bridge Functions</a><br>- <a href="#c4ef">Function Types / Lambdas</a><br>- <a href="#8111">Conclusion</a></p><h3>Extension Functions</h3><p>Extension functions are IMHO one of the most powerful features of Kotlin. It allows you to extend existing classes, even if you don’t have access to the source code. There is no need to bloat classes with functions needed only in edge cases, just add extension functions to where you need them. Also it allows you to create scoped lambdas, which can only be called on a given receiver, which is the base for creating DSLs in Kotlin. Extension functions are heavily used in the Kotlin standard library, let’s take a the max() function as an example.</p><pre>val x = listOf(1, 2, 3).max()</pre><p>It is not a member function of List, but an extension function to Iterable. The signature of the function is:</p><pre>fun &lt;T : Comparable&lt;T&gt;&gt; Iterable&lt;T&gt;.max(): T? </pre><p>But how is the Iterable instance — the so-called receiver — passed to the function? Let’s take a look at the generated java code:</p><pre>public static final Comparable max(@NotNull Iterable $this$max) </pre><p>So it is just a static function, which takes the receiver as the first parameter. The Iterableclass is not touched at all, that’s why you may only access public members of the class.</p><h3>Multiple Receivers</h3><p>No doubt extension functions are quite powerful, so what’s missing? Let’s see the <a href="https://youtrack.jetbrains.com/issue/KT-10468">original feature request by Damian Wieczorek</a> for multiple receivers. The idea is to allow specifying multiple receivers for a function, so you can use them in the body of the function.<br> <br><em>This can be extremely useful when dealing with third-party libraries or frameworks which require extending their own classes. Currently, the common thing to do is implement them within an interface that must be implemented in each class. For example (in Android), to create an extension function Float.dp() to use within a View:</em></p><pre>fun (View, Float).dp() = this * resources.displayMetrics.density<br>// explicitly: fun (View, Float).dp() = this@Float * this@View.resources.displayMetrics.density<br><br>class SomeView : View {<br>    val someDimension = 4f.dp()<br>}</pre><p>The idea was to be able to write extension functions that have access to an additional receiver, which is passed as some kind of scope. The first implementation of <a href="https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md">context receivers</a>, as they were called at that time, allowed specifying multiple receivers for a (extension) function. Let’s see how it works in practice using the example above.</p><pre>context(View)<br>fun Float.dp()= this * resources.displayMetrics.density<br><br>class SomeView : View {<br>    val someDimension = 4f.dp()<br>}</pre><p>So context defines a kind of scope for the (extension) function, which must be present to call the function. Technically, the context receivers are passed as additional parameters to the function: at first the context receivers, than the (optional) receiver, followed by the regular parameters. So the generated java code looks like this:</p><pre>public static final float getDp(@NotNull View $context_receiver_0, float $this$dp) </pre><h3>Context Parameters</h3><p>Context receivers have been experimental for quite a while, and that time has been used for clarification of the use cases. Besides some restrictions, the main difference is that the parameters are now named. Using our example above, we must write:</p><pre>context(view:View)<br>fun Float.dp()= this * view.resources.displayMetrics.density</pre><p>So you must explicitly use the named reference view to access the context receiver, you cannot use this@View anymore; at least if you need to reference the context receiver in the body of the function. If you just pass it as a scope for calling other functions, you can use anonymous parameters. Let’s add a Int.dp() variant that just delegates to the Float extension. Since we do not reference the receiver (but just pass it) we can declare the context parameter as anonymous:</p><pre>context(_:View)<br>fun Int.dp() = this.toFloat().dp()<br><br>class SomeView : View {<br>    val someDimension = 4.dp()<br>}</pre><h3>Use Cases</h3><p>We will now examine some use cases for context parameters inspired by the examples given in the <a href="https://github.com/Kotlin/KEEP/blob/context-parameters/proposals/context-parameters.md">original proposal</a>.</p><h4>Depencency Injection / Implicit Services</h4><p>Let’s take a look at the following example:</p><pre>class SomeService {<br><br>    private val log = LoggerFactory.getLogger(javaClass)<br><br>    fun someFunction() {<br>       performOperation(&quot;some parameter&quot;)<br>    }<br>    <br>    fun performOperation(param: String) {<br>        // do some operation and log result<br>        log.info(&quot;successfully performed operation with param: $param&quot;)<br>    }<br>}</pre><p>Now you have another service that like to reuse the performOperation() function, but you don’t want to depend on the SomeService class and for sure don’t want to copy the code. You could extract it as a function, but then you have to pass the logger as a parameter, which is not very nice, since it is not a <em>real</em> parameter of the function, but more like a technical dependency needed by the implementation of function. You could use a global logger, but that is not a good idea either, since you want to use a dedicated logger for each class. Here is where context parameters come into play.</p><pre>class SomeService {<br>    private val log = LoggerFactory.getLogger(javaClass)<br><br>    fun someFunction() {<br>        with(log) {  // provide context using the with() function<br>            performOperation(&quot;some parameter&quot;)<br>        }<br>    }<br>}<br><br>context(log:Logger)<br>fun performOperation(param: String) {<br>    // do some operation and log result<br>    log.info(&quot;successfully performed operation with param: $param&quot;)<br>}<br><br>class OtherService {<br>    private val log = LoggerFactory.getLogger(javaClass)<br><br>    fun otherFunction() {<br>        context(log) {  // provide context using the context() function<br>            performOperation(&quot;other parameter&quot;)<br>        }<br>    }<br>}</pre><p>For sure, the logger is also a parameter, but the signature of the function has not changed and is much cleaner.</p><p>Be aware the services use two different functions to provide context: SomeService uses the <em>old</em> with() which is always used to pass receivers. But you can only pass one receiver using this function, if you want to pass more, you have to nest them:</p><pre>with(log) {<br>    with(anotherContext) {<br>        performOperation(&quot;some parameter&quot;)<br>    }<br>}</pre><p>With the new context() function, you can simply write:</p><pre>context(log, anotherContext) {<br>    performOperation(&quot;some parameter&quot;)<br>}</pre><blockquote>Some folks complaint in the discussion that this might be confusing, as you use the wording context for both demanding and also providing context, what do you think?</blockquote><p>You can use context parameters for properties as well. Let’s take a look at the following example. We have a class Guest which has a firstName and lastNameproperty, which is loaded from a database. We also have a service called GuestImageUriProvider that retrieves the URI of the guest image from another system.</p><pre>data class Guest(val id:GuestId, val firstName: String, val lastName: String)<br><br>interface GuestImageUriProvider {<br>    fun getGuestImageUri(guestId: GuestId): URI<br>}</pre><p>We could write an extension function to retrieve the URI of the guest image passing GuestImageUriProvider as a context parameter.</p><pre>context(guestImageUriProvider: GuestImageUriProvider)<br>fun Guest.getImageUri() =<br>    guestImageUriProvider.getGuestImageUri(id)</pre><p>But we could as well write a property for the Guest class, which is cleaner and easier to read:</p><pre>context(guestImageUriProvider: GuestImageUriProvider)<br>val Guest.imageUri: URI<br>    get() = guestImageUriProvider.getGuestImageUri(id)<br><br>...<br>with(guestImageUriProvider) {<br>    println(&quot;Guest ${guest.lastName} with image URI: ${guest.imageUri}&quot;)<br>}</pre><h4>Scoped Functions</h4><p>Some functions are only valid in a certain scope, e.g. when dealing with a database transaction. And wouldn’t it be nice if we could let the compiler check this for us? Let’s take a look at the following example. We have a function doSomething() that is only valid in the scope of a transaction, so we require it to be called with a context parameter Transaction. In our case here, this is just a marker interface, and since we don’t use it in our code, it can be anonymous. The doSomething() function calls another function doSomeMoreStuff(), which is supposed to be executed in the same transaction.</p><pre>interface Transaction<br><br>context(_: Transaction)<br>fun doSomething() {<br>    // some operations<br>    // ...<br>    doSomeMoreStuff()<br>}<br><br>context(_: Transaction)<br>fun doSomeMoreStuff() {<br>    // some operations<br>    // ...<br>}</pre><p>If we now try to call doSomething() without a transaction, the compiler will complain:</p><pre>doSomething() // &quot;No context argument for &#39;Transaction&#39; found.&quot;</pre><p>Let’s say we have a database repository that supports transactions. We could write a function transactional() that takes a block of code and execute it in the context of a transaction:</p><pre>class DbTransaction : Transaction {<br>    fun begin(): Unit = TODO()<br>    fun commit(): Unit = TODO()<br>    fun rollback(): Unit = TODO()<br>}<br><br>class DbRepository {<br><br>    fun &lt;T&gt; transactional(block: context(Transaction) () -&gt; T): T =<br>        with(DbTransaction()) {<br>            begin()<br>            return try {<br>                block().also {<br>                    commit()<br>                }<br>            } catch (e: Exception) {<br>                rollback()<br>                throw e<br>            }<br>        }<br> ...<br>}</pre><p>Watch the type of the block parameter context(Transaction) () -&gt; T, which means that the given block must be called in the context of a Transaction. Now we can use the transactional() function to execute our code in the context of a transaction, and the compiler is satisfied:</p><pre>val repository = DbRepository()<br><br>val result = repository.transactional {<br>    doSomething()<br>}</pre><h4>Externally implemented Interfaces / Type Classes</h4><p>Externally implemented interfaces allows you to provide an implementation of an interface for a given type, without the need to modify the type itself. In Haskell this is done using type classes, if you are familiar with Rust, think of traits. You can do something similar (*) in Kotlin using context parameters. We will take the Comparable and Comparator interfaces to illustrate this. We have a function max() that takes two parameters of type T and returns the maximum of the two. The type T must implement the Comparable interface, so we can compare the two values.</p><pre>fun &lt;T : Comparable&lt;T&gt;&gt; max(x: T, y: T) = if (x &gt; y) x else y</pre><p>But what if we want to compare two values of a type that does not implement the Comparable interface? We get a compile error, since the type T does not implement the Comparable interface.</p><pre>fun &lt;T&gt; max(x: T, y: T) = if (x &gt; y) x else y<br>//                              ^ <br>// Unresolved reference. None of the following candidates is<br>// applicable because of a receiver type mismatch:<br>// fun String.compareTo(other: String, ignoreCase: Boolean = ...): Int</pre><p>There is no generic compareTo() function, so we have to implement our own: If we have a Comparator for the type T, we can use it to compare the two values. And that’s where context parameters come into play:</p><pre>context(comparator: Comparator&lt;T&gt;)<br>operator fun &lt;T&gt; T.compareTo(other: T): Int = comparator.compare(this, other)</pre><p>So if we now add the Comparator as a context parameter to our max() function, we can use the generic compareTo() function:</p><pre>context(_: Comparator&lt;T&gt;)<br>fun &lt;T&gt; max(x: T, y: T) = if (x &gt; y) x else y  // compiler is satified</pre><p>Now we can use the max() function with any type, as long as we provide a Comparator for the type. Let’s take a look at the following example:</p><pre>// our type User is not comparable <br>data class User(val name: String)<br><br>// we have an externally implemented comparator for User<br>val userComparator = object : Comparator&lt;User&gt; {<br>    override fun compare(o1: User, o2: User): Int {<br>        return o1.name.length - o2.name.length<br>    }<br>}<br><br>val user = User(&quot;Ralf&quot;)<br>val user2 = User(&quot;Ralf2&quot;)<br><br>// we can use the generic max function in the context of the comparator<br>with(userComparator) {<br>    println(max(user, user2)) // Ralf2<br>}</pre><p>Okay, comparing users by their name length is not very useful, but you get the idea. You can call the function with any type as long as you provide a Comparator for it.</p><blockquote>(*) As said above, it is just similar to type classes or traits. The difference is, that with Kotlin Context Parameters you must explicitly provide the context. In Haskell resp. Rust there is no need for that, the compiler automatically finds any suitable implementation in scope, which is quite more elegant.</blockquote><h4>DSLs</h4><p>Another use case for context parameters given in the Keep is to create resp. extends DSLs. Let’s take a look at the following example, that let us configure routes for a webserver.</p><pre>typealias RequestHandler = () -&gt; Unit<br><br>data class Route(<br>    val method: HttpMethod,<br>    val path: String,<br>    val handler: RequestHandler)<br><br>data class Server(val routes: List&lt;Route&gt;)<br><br>class RouteBuilder {<br>    private val routes = mutableListOf&lt;Route&gt;()<br><br>    fun addRoute(method: HttpMethod, path: String, handler: RequestHandler) {<br>        routes += Route(method, path, handler)<br>    }<br><br>    fun build(): List&lt;Route&gt; = routes.toList()<br>}<br><br>class ServerBuilder {<br>    private val routeBuilder = RouteBuilder()<br><br>    fun routes(block: RouteBuilder.() -&gt; Unit) {<br>        routeBuilder.apply(block)<br>    }<br><br>    fun build(): Server = Server(routeBuilder.build())<br>}<br><br>fun server(block: ServerBuilder.() -&gt; Unit): Server =<br>    ServerBuilder().apply(block).build()<br><br>...<br><br>server {<br>    routes {<br>        addRoute(GET, &quot;/home&quot;, { println(&quot;GET /home handler&quot;) })<br>        addRoute(POST, &quot;/submit&quot;, { println(&quot;POST /submit handler&quot;) })<br>    }<br>}</pre><p>We want to enhance the readability of the DSL by allowing a natural language to define routes, avoiding the need to call a function addRoute() explicitly. Our target DSL should look like this:</p><pre>routes {<br>    GET to &quot;/home&quot; handle { println(&quot;GET /home handler&quot;) }</pre><p>To achieve this, we need two infix functions to and handle. Kotlin already has an infix function to for creating pairs</p><pre>  infix fun &lt;A, B&gt; A.to(that: B): Pair&lt;A, B&gt; = Pair(this, that)</pre><p>so we can use it to create a pair of HttpMethod and String:</p><pre>GET to &quot;/home&quot;   </pre><p>What’s left is to create the handle infix function as an extension on Pair&lt;HttpMethod,String&gt; that takes a RequestHandler. A problem is that the handle function needs to be defined in the RouteBuilder so we can add the route. Alas, we do not have access to it, since it is third party code. And we cannot define an extension function on RouteBuilder, since the infix function is already an extension on Pair. But we may provide a context parameter RouteBuilder to define an additional receiver, and now we can call the addRoute() function:</p><pre>context(routeBuilder:RouteBuilder)<br>infix fun Pair&lt;HttpMethod, String&gt;.handle(handler: () -&gt; Unit) {<br>    routeBuilder.addRoute(this.first, this.second, handler)<br>}</pre><p>That’s it, our DSL now works as expected :-)</p><pre>server {<br>    routes {<br>        GET to &quot;/home&quot; handle { println(&quot;GET /home handler&quot;) }<br>        POST to &quot;/submit&quot; handle { println(&quot;POST /submit handler&quot;) }<br>    }<br>}</pre><h3>Bridge Functions</h3><p>One (of the) complaint(s) that came with the change from context receivers to parameters, is that you have to name them in order to use them. This might be undesirable in certain situations like e.g. DSLs. Take the following function using the DSL from above that works fine with former <strong>context receivers</strong>:</p><pre>context(ServerBuilder)<br>fun addServerConfig() {<br>    routes {<br>        GET to &quot;/home&quot; handle { println(&quot;GET /home handler&quot;) }<br>        POST to &quot;/submit&quot; handle { println(&quot;POST /submit handler&quot;) }<br>    }<br>}</pre><p>With <strong>context parameters</strong>, you have to explicitly name the server parameter and reference it; there is no implicit receiver:</p><pre>context(server:ServerBuilder)<br>fun addServerConfig() {<br>    server.routes {<br>        GET to &quot;/home&quot; handle { println(&quot;GET /home handler&quot;) }<br>        POST to &quot;/submit&quot; handle { println(&quot;POST /submit handler&quot;) }<br>    }<br>}</pre><p>To come around this situation, the Keep suggests writing a so-called bridge function, a (global) function that does the dereferencing for you:</p><pre>context(server:ServerBuilder)<br>fun routes(block: RouteBuilder.() -&gt; Unit) = server.routes(block)<br><br>context(server:ServerBuilder)<br>fun addServerConfig() {<br>    routes {<br>        GET to &quot;/home&quot; handle { println(&quot;GET /home handler&quot;) }<br>        POST to &quot;/submit&quot; handle { println(&quot;POST /submit handler&quot;) }<br>    }<br>}</pre><p>This is tedious, but if you need that, there is at least a workaround.</p><h3>Functions Types / Lambdas</h3><p>We have already seen that we can declare context parameters on function types in the part on scoped functions. But how can we actually use them in lambdas. We have a lambda that demands a User passed as parameter and a Logger as context parameter:</p><pre>val lambda : context(Logger) (User) -&gt; Unit = {<br>    // TODO log given user<br>}</pre><p>Currently, named context parameters are not supported in function types, so how do I reference the Logger to e.g. log the given user? The Kotlin standard lib provides a helper function that allows us to retrieve the context parameter of a given type:</p><pre>context(context: A)<br>inline fun &lt;A&gt; contextOf(): A = context</pre><p>The point is that this function uses a named reference context which is then used as the return value. We can use this function to retrieve the context parameters in our lambda:</p><pre>val lambda : context(Logger) (User) -&gt; Unit = {<br>    val log = contextOf&lt;Logger&gt;()<br>    log.info(&quot;user is $user&quot;)<br>}</pre><p>Now how do we actually pass the context parameter to the lambda? At last, these are just parameters, so we can call it in two ways: either pass the Logger as formal context or also as a regular parameter:</p><pre>val logger = LoggerFactory.getLogger(&quot;console&quot;)<br>val user = User(&quot;Ralf&quot;)<br><br>// pass logger as context<br>context(logger) {<br>    lambda(user)<br>}<br>    <br>// pass both as parameters<br>lambda(logger, user)</pre><p>See more examples on lambdas in the accompanying <a href="https://github.com/ralfstuckert/kotlin-context-parameters">Github repository</a>.</p><h3>Conclusion</h3><p>Context parameters are an interesting feature in Kotlin, which allows you to create functions with multiple receivers. Be aware that some of the examples above (and in the Keep) could be solved using plain extension functions, but the context parameters allow you to create scoped functions with multiple receivers, which comes handy if you want to write extension functions that need access to (an)other receiver(s). If you are writing libraries or frameworks, it might make sense to use context parameters consistently, since the context is passed from one function call to another. After all, they are in preview at the moment, let’s see how they’ll evolve in the future.</p><p>You will find the the source code and some more examples in the accompanying <a href="https://github.com/ralfstuckert/kotlin-context-parameters">Github repository</a>.</p><blockquote>For me context is the key — from that comes the understanding of everything.<br><a href="https://en.wikipedia.org/wiki/Kenneth_Noland">Kenneth Noland</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0156f2911462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Storage Development with Azurite — Part II Testing]]></title>
            <link>https://medium.com/@ralf.stuckert/azure-storage-development-with-azurite-part-ii-testing-493dbf6ea0de?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/493dbf6ea0de</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[azurite]]></category>
            <category><![CDATA[azure-stor]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 10:57:22 GMT</pubDate>
            <atom:updated>2024-04-08T10:57:22.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Storage Development with Azurite — Part II Testing</h3><blockquote>The f<a href="https://medium.com/@ralf.stuckert/azure-storage-development-with-azurite-part-i-1cfc502ab0f2">irst part</a> was about setting up Azurite and using it for local development, and how the Azure Storage Explorer can be helpful in interacting with the storage. In this second part we will use Azurite as a testcontainer for medium size Unit and Spring Integration tests.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cmnu7-sEbbiqKYLj" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the first part we were using <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite">Azurite</a> as an Azure Storage replacement for local development, and we used the <a href="https://azure.microsoft.com/products/storage/storage-explorer">Azure Storage Explorer</a> to inspect and interact with blobs and queues. Now we are using Azurite as a <a href="https://testcontainers.com/">testcontainer</a> in order to write <a href="https://testing.googleblog.com/2010/12/test-sizes.html">medium size</a> Unit and Spring Integration tests. The example project shown here is <a href="https://github.com/ralfstuckert/spring-azurite-demo">provided on Github</a>.</p><h3>Setting up a Testcontainer</h3><p>I assume you are familiar with <a href="https://testcontainers.com/">testcontainer</a>s, if not, the <a href="https://testcontainers.com/getting-started">Getting Started</a> and the <a href="https://testcontainers.com/guides/">Guides</a> are a good starting point. In short, they allow you to set up external dependencies like databases, messaging middleware etc. as a Docker Container in order to run integration tests against it. To run Testcontainers-based tests, you need a Docker-API compatible container runtime as a prerequisite.</p><p>To get started we will write a <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/test/kotlin/com/github/ralfstuckert/springazuritedemo/AzuriteTestcontainer.kt">base class</a> which sets up the testcontainer and provides some useful other stuff needed by the actual test.</p><pre>class AzuriteContainer : GenericContainer&lt;AzuriteContainer&gt;(&quot;mcr.microsoft.com/azure-storage/azurite:3.29.0&quot;)<br><br>abstract class AzuriteTestcontainer()  {<br><br>    companion object {<br>        val container = AzuriteContainer().withExposedPorts(10000, 10001, 10002)<br>...<br>        init {<br>            container.start()<br>        }<br>...<br>    }<br><br>}</pre><p>So we are creating a testcontainer using the image <strong>mcr.microsoft.com/azure-storage/azurite</strong>, and expose the ports 10000, 10001 and 10002 which are the ports for the blob-, queue- and table-storage respectively. In the init block of the companion object we start the container. So the container will be started just once if you are running a multiple tests, so it is quite cheap after all.</p><p>Testcontainers do not map the given ports right away to the host system, but use random ports. This is done to avoid port collisions, see more details in the <a href="https://java.testcontainers.org/features/networking/">network section</a> of the documentation. So in order to provide the correct ports to our tests, we add the following code:</p><pre>val blobUrl by lazy {<br>    &quot;http://${container.host}:${container.getMappedPort(10000)}&quot;<br>}<br>val queueUrl by lazy {<br>    &quot;http://${container.host}:${container.getMappedPort(10001)}&quot;<br>}<br>val tableUrl by lazy {<br>    &quot;http://${container.host}:${container.getMappedPort(10002)}&quot;<br>} </pre><p>We retrieve the mapped port — means the random port actually chosen — for the corresponding original port. Instead of localhost (or 127.0.0.1) we also use the term <a href="https://java.testcontainers.org/features/networking/#getting-the-container-host">container.host</a>. In local environments this usually is localhost, but on CI systems it may be a different host. For our convenience, we also provide the resulting connection strings</p><pre>val blobConnectionString by lazy { &quot;DefaultEndpointsProtocol=http;AccountName=${accountName};AccountKey=${accountKey};BlobEndpoint=${blobUrl}/devstoreaccount1;&quot; }<br>val queueConnectionString by lazy { &quot;DefaultEndpointsProtocol=http;AccountName=${accountName};AccountKey=${accountKey};QueueEndpoint=${queueUrl}/devstoreaccount1;&quot; }<br>val tableConnectionString by lazy { &quot;DefaultEndpointsProtocol=http;AccountName=${accountName};AccountKey=${accountKey};TableEndpoint=${tableUrl}/devstoreaccount1;&quot; }</pre><h3>AzureBlobStorage Test</h3><p>Now we will write a test for the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/kotlin/com/github/ralfstuckert/springazuritedemo/AzureBlobStorage.kt"><strong>AzureBlobStorage</strong></a>, which provides access to the blobs in a given container; let’s recap the implementation:</p><pre>@Service<br>class AzureBlobStorage(val blobServiceClient: BlobServiceClient,<br>    @Value(&quot;\${demo.storage.blob.container}&quot;) val containerName: String<br>) {<br><br>...<br><br>    fun listBlobNames():List&lt;String&gt; = ...<br>     <br>    fun downloadBlob(blobName: String): ByteArray = ...</pre><p>So our service class needs a <strong>BlobServiceClient </strong>and the name of the container as constructor parameters, which will be injected by Spring at runtime. Our Unit Test will set up the service and therefore needs the appropriate objects, which will be created right away using the <strong>blobConnectionString</strong> provided by our <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/test/kotlin/com/github/ralfstuckert/springazuritedemo/AzuriteTestcontainer.kt"><strong>AzuriteTestcontainer</strong></a> base class:</p><pre>class AzureBlobStorageTest : AzuriteTestcontainer() {<br><br>    val container = &quot;test&quot;<br>    val client = BlobServiceClientBuilder()<br>        .connectionString(blobConnectionString)<br>        .buildClient()<br>    val blobContainerClient = client.getBlobContainerClient(container)<br>    val storageService = AzureBlobStorage(client, container)<br><br>    @BeforeEach<br>    fun setup() {<br>        if (blobContainerClient.exists()) {<br>            blobContainerClient.listBlobs().map { it.name }.forEach {<br>                blobContainerClient.getBlobClient(it).delete()<br>            }<br>        }<br>    }</pre><p>Since we are reusing the same Azurite instance for all tests, we have to properly clean up everything before each test.</p><p>Now we are ready to write the first tests, let’s start with the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/test/kotlin/com/github/ralfstuckert/springazuritedemo/AzureBlobStorageTest.kt#L26-L35"><strong>listBlobNames</strong>()</a> function. It is expected to return a list with the names of the blobs in the given container.</p><pre>@Test<br>fun listBlobNames() {<br>    storageService.listBlobNames() shouldBe emptyList()<br><br>    blobContainerClient.getBlobClient(&quot;a&quot;).upload(&quot;aaa&quot;.byteInputStream())<br>    blobContainerClient.getBlobClient(&quot;b&quot;).upload(&quot;bbb&quot;.byteInputStream())<br>    blobContainerClient.getBlobClient(&quot;c&quot;).upload(&quot;ccc&quot;.byteInputStream())<br><br>    storageService.listBlobNames() shouldBe listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>}</pre><p>Initially we expected the service to return an empty list, as there are no blobs in the container. We manually add some blobs using the <strong>blobContainerClient</strong> created for our test setup, and now expect a list of the blob names. If we run the test, the base class will start the Azurite container, you will find log statements on that like the following. At the end of the test suite the <a href="https://github.com/testcontainers/moby-ryuk">Ryuk container</a> that is started by Testcontainers core will take care of stopping the singleton container.</p><pre>20:31:04.822 ... Creating container for image: mcr.microsoft.com/azure-storage/azurite:3.29.0<br>20:31:06.235 ... Container mcr.microsoft.com/azure-storage/azurite:3.29.0 started in PT1.413205S</pre><p>So if we run our test it sets up the our AzureBlobStorage using the connection string and our test will run against Azurite testcontainer instance, and…. tada, green :-) This test is not a big deal and you may wonder if all this is overkill, but when it comes to testing edge cases and failure handling, testing against <em>the real thing</em> by utilizing testcontainers is quite valuable.</p><h3>Spring Integration Test</h3><p>In our <strong>AzureBlobStorageTest</strong> we didn’t use any Spring magic, we created our setup in order to connect to Azurite <em>by hand.</em> In order to test our <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/kotlin/com/github/ralfstuckert/springazuritedemo/MessageReceiver.kt"><strong>MessageReceiver</strong></a> we will write a Spring Integration Test, which will start up a complete Spring Boot Application with all the configuration and injection magic that Spring performs.</p><pre>@ActiveProfiles(&quot;azurite&quot;)<br>@SpringBootTest<br>class MessageReceiverTest:AzuriteTestcontainer() {<br><br>    @MockkBean()<br>    lateinit var messageHandlerMock: DemoMessageHandler<br><br>    @Autowired<br>    lateinit var storageQueueTemplate: StorageQueueTemplate<br><br>    val messageSlot = slot&lt; Message&lt;*&gt;&gt;()<br><br>    @BeforeEach<br>    fun setup() {<br>        clearAllMocks()<br>    }<br><br>    @Test<br>    fun `receive message`() {<br>        every { messageHandlerMock.handleMessage(capture(messageSlot)) } just Runs<br><br>        storageQueueTemplate.send(DEMO_QUEUE, MessageBuilder.withPayload(&quot;Yeehaw&quot;).build())<br><br>        val message = messageSlot.awaitMessage()<br>        message.text() shouldBe &quot;Yeehaw&quot;<br>    }<br>....<br></pre><p>Due to the SpringBootTest annotation the complete Spring application will be started during the test. We demand to use the <strong>azurite profile</strong>, so our application under test will be set up using the configuration data provided in <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/resources/application-azurite.yaml"><strong>application-azurite.yaml</strong></a>. The we <a href="https://github.com/Ninja-Squad/springmockk">mockk</a> our DemoMessageHandler so we can setup custom behavior in our test, resp. in this case we will set up the mock handler to <a href="https://mockk.io/#capturing">capture</a> the message passed, so we can inspect it.</p><p>In order to test our message handler, we send a message to our demo queue, wait for the handler to receive the message, and check if the content is the same. If you run the test you will notice that it takes quite a bit more time than our other tests. This is due to the fact that the complete application ist started which will be reflected in the logs. Run the test, and…red…eh? If you look at the logs you will find something like:</p><pre>Connection refused: /127.0.0.1:10002</pre><p>Ah, ok. We used the azurite profile for our test, and in the <strong>application-azurite.yaml</strong> the configuration for azurite is set up to localhost:10000–10002…but — as already mentioned — the testcontainer uses random ports. So how do we get those ports into our test setup? We will use <a href="https://www.baeldung.com/spring-dynamicpropertysource">DynamicPropertySource</a> to inject (resp. overwrite) the values in the Spring environment in order to use the correct hosts and ports, by adding the following code to our <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/test/kotlin/com/github/ralfstuckert/springazuritedemo/AzuriteTestcontainer.kt#L37-L45"><strong>AzuriteTestcontainer</strong></a> base class:</p><pre>abstract class AzuriteTestcontainer()  {<br><br>    companion object {<br>        ...<br><br>        @JvmStatic<br>        @DynamicPropertySource<br>        fun registerAzuriteProperties(registry: DynamicPropertyRegistry) {<br>            registry.add(&quot;demo.storage.table.endpoint&quot;) { &quot;${tableUrl}/devstoreaccount1&quot; }<br><br>            // overwrite endpoints using the testcontainers ports<br>            registry.add(&quot;spring.cloud.azure.storage.blob.endpoint&quot;) { &quot;${blobUrl}/devstoreaccount1&quot; }<br>            registry.add(&quot;spring.cloud.azure.storage.queue.endpoint&quot;) { &quot;${queueUrl}/devstoreaccount1&quot; }<br>        }</pre><p>Now run the test again, and….tada, green :-) In productive code we would add some more tests in order to check failure- and timeout-handling etc.</p><h3>Playtika Spring Boot Testcontainers</h3><p>If you write medium sized SpringBootTests like our latter one, it is worth to have a look at the <a href="https://github.com/PlaytikaOSS/testcontainers-spring-boot">https://github.com/PlaytikaOSS/testcontainers-spring-boot</a> project. It provides out-of-the-box testcontainers with autoconfiguration for Spring Boot. So you just need to add the dependency, and the testcontainer will be ready to be used in your SpringBootTest. And they have images for all kinds of stuff: databases of all flavors, mailserver, messaging and cloud stuff of all three major vendors. So just give it a try. As an example we will now rewrite our MessageReceiverTest in order to make use of the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/test/kotlin/com/github/ralfstuckert/springazuritedemo/PlaytikaMessageReceiverTest.kt">Playtika variant</a> of the Azurite testcontainer:</p><pre>@ActiveProfiles(&quot;playtika&quot;)<br>@EnableAutoConfiguration<br>@SpringBootTest<br>class PlaytikaMessageReceiverTest {<br><br>    @MockkBean()<br>    lateinit var messageHandlerMock: DemoMessageHandler<br><br>    @Autowired<br>    lateinit var storageQueueTemplate: StorageQueueTemplate<br><br>    val messageSlot = slot&lt; Message&lt;*&gt;&gt;()<br><br>    @BeforeEach<br>    fun setup() {<br>        clearAllMocks()<br>    }<br><br>    @Test<br>    fun `receive message`() {<br>        every { messageHandlerMock.handleMessage(capture(messageSlot)) } just Runs<br><br>        storageQueueTemplate.send(DEMO_QUEUE, MessageBuilder.withPayload(&quot;Yeehaw&quot;).build())<br><br>        val message = messageSlot.awaitMessage()<br>        message.text() shouldBe &quot;Yeehaw&quot;<br>    }</pre><p>This variant is quite similar to our first MessageRetrieverTest, except for the following points:</p><ol><li>It does NOT inherit from a common base class that deals with the container set up.</li><li>It uses a dedicated profile <strong>playtika</strong></li><li>We have to enable auto-configuration</li></ol><p>So where is the container setup done? This is done by to Spring auto-configuration, provided by the dependency we are adding in our <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/build.gradle.kts#L51-L52">build.gradle.kts</a>. The first adds the embedded Azurite which does the setup of the container (and some more stuff), the second is needed to get things working, see the <a href="https://github.com/PlaytikaOSS/testcontainers-spring-boot?tab=readme-ov-file#how-to-use">documentation</a> for information on that:</p><pre>testImplementation((&quot;com.playtika.testcontainers:embedded-azurite:3.1.5&quot;))<br>testImplementation(&quot;org.springframework.cloud:spring-cloud-starter-bootstrap&quot;)</pre><p>The embedded-azurite provides the azurite specific host and ports in some <a href="https://github.com/PlaytikaOSS/testcontainers-spring-boot/tree/develop/embedded-azurite">dedicated properties</a> in the Spring environment. We just have to wire them up, that’s we are using a dedicated profile <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/resources/application-playtika.yaml"><strong>application-playtika.yaml</strong></a>:</p><pre>demo:<br>  storage:<br>    table:<br>      endpoint: ${embedded.azurite.table-endpoint}<br><br>spring:<br>  cloud:<br>    azure:<br>      storage:<br>        blob:<br>          account-name: ${embedded.azurite.account-name}<br>          endpoint: ${embedded.azurite.blob-endpoint}<br>          account-key: ${embedded.azurite.account-key}<br>        queue:<br>          account-name: ${embedded.azurite.account-name}<br>          endpoint: ${embedded.azurite.queue-endpoint}<br>          account-key: ${embedded.azurite.account-key}<br>          queue-name: testqueue</pre><p>Just run the test and you will see quite the same output as our original MessageReceiverTest produced. As already said you will find images for all kinds of stuff like database etc., perfectly prepared and ready to run, very nice. A drawback is, that it is built to be used in full fledged SpringBootTests, but you may not use it in more <em>light-weight</em> tests as we did in our first example.</p><h3>Conclusion</h3><p><a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite">Azurite</a> can be quite helpful when it comes to developing applications that uses the Azure Storage APIs, be it as a local replacement in order to run your app, or for writing medium sized or even full fledged Spring Integration Tests by using Azurite as a testcontainer. Have an eye on the <a href="https://github.com/PlaytikaOSS/testcontainers-spring-boot">Playtika Spring Boot testcontainers</a> if you intend to write integration tests in general, as they provide out-of-the-box solutions for all kinds of external dependencies, that are easily integrated by auto-configuration. And check out the <a href="https://azure.microsoft.com/products/storage/storage-explorer">Azure Storage Explorer</a> if you have not already used it yet; it is a free tool that comes in handy, just give it a try.</p><blockquote>Experience is a hard teacher because she gives the test first, the lesson afterward. <br><a href="https://en.wikipedia.org/wiki/Vern_Law">Vernon Law</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493dbf6ea0de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Storage Development with Azurite — Part I]]></title>
            <link>https://medium.com/@ralf.stuckert/azure-storage-development-with-azurite-part-i-1cfc502ab0f2?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cfc502ab0f2</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[azure-storage]]></category>
            <category><![CDATA[azurite]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 11:08:16 GMT</pubDate>
            <atom:updated>2024-04-08T17:54:09.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Storage Development with Azurite — Part I</h3><blockquote>Developers use containers for local development and testing, be it databases of all flavors, authorization server, messaging middleware or whatsoever. This article will show the usage of Azurite, a lightweight server clone of Azure Storage. The first part will be on setup in order to use the BlobStorage, TableStorage and Queue-APIs, the <a href="https://medium.com/@ralf.stuckert/azure-storage-development-with-azurite-part-ii-testing-493dbf6ea0de">second part</a> will be on testing using Azurite testcontainer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dGvIQAHmwdHShela" /><figcaption>Photo by <a href="https://unsplash.com/@joshstyle?utm_source=medium&amp;utm_medium=referral">JOSHUA COLEMAN</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you develop applications for Azure Cloud you might have used the Blob Storage for easy persistence of unstructured resp. binary data. The API is quite easy, you may access the data via URL, even without security. Maybe you have also used Storage Queues or the Table Storage, which is a fast solution for accessing tabular data by key. Developing against these APIs is straightforward, all you need is some credential, preferably an <a href="https://learn.microsoft.com/en-us/azure/developer/java/sdk/identity">identity</a>. But if you develop against a storage account you have to share the storage, which means you have to manage access so you don’t interfere with each other.</p><p>But currently we are used to access our external dependencies like databases by utilizing Containers: just start it on your local machine and run your application and tests agains it. This has a lot of advantages: you do not interfere with others, and you do not even need an internet connection, so you can develop wherever you are, be it on the train or in the middle of nowhere. There are images for all kinds of stuff that makes local development easy: databases of all flavors, messaging middleware…and there is <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite">Azurite</a>, a storage emulator with support for Blob Containers, Queues and Tables.</p><p>In this first article we will use Azurite to develop a Kotlin Spring Boot sample application, the second part will show how to run medium size Unit and Spring Integration Test with an Azurite testcontainer. We will also use the <a href="https://azure.microsoft.com/products/storage/storage-explorer/">Azure Storage Explorer</a>, a tiny UI based tool that makes introspection of the storage quite easy. The source code is <a href="https://github.com/ralfstuckert/spring-azurite-demo">provided on Github</a>.</p><h3>Starting Azurite</h3><p>The <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite">Azurite</a> open-source emulator provides a free local environment for testing your Azure Blob, Queue Storage, and Table Storage applications. There are multiple choices to run the emulator:</p><ul><li>As an <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code%2Cblob-storage#run-azurite">extension for Visual Studio Code</a></li><li>As a <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=npm%2Cblob-storage#run-azurite">Node Module</a></li><li>As a <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=docker-hub%2Cblob-storage#run-azurite">Docker Image</a></li></ul><p>We will utilize the docker image, just run the image:</p><pre>docker run -it -p 10000:10000 -p 10001:10001 -p 10002:10002 mcr.microsoft.com/azure-storage/azurite<br><br>2024-03-06 05:52:14 Azurite Blob service is starting at http://0.0.0.0:10000<br>2024-03-06 05:52:14 Azurite Blob service is successfully listening at http://0.0.0.0:10000<br>2024-03-06 05:52:14 Azurite Queue service is starting at http://0.0.0.0:10001<br>2024-03-06 05:52:14 Azurite Queue service is successfully listening at http://0.0.0.0:10001<br>2024-03-06 05:52:14 Azurite Table service is starting at http://0.0.0.0:10002<br>2024-03-06 05:52:14 Azurite Table service is successfully listening at http://0.0.0.0:10002</pre><p>So all we gotta do is map the ports, 10000 for the BlobStorage, 10001 is the TableStorage and 10002 the StorageQueue. If you want your storage data to persist just mount the volume <strong>/data</strong></p><pre>docker run -it -p 10000:10000 -p 10001:10001 -p 10002:10002 -v ./data:/data mcr.microsoft.com/azure-storage/azurite:3.29.0-arm64</pre><h3>Connecting to Azurite</h3><p>In order to connect to the azurite storage we need to provide an endpoint, an account-name and an account-key. The account-name is set to <strong>devstoreaccount1</strong>, also the account-key is fixed, you will find them both in the <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cblob-storage#connect-to-azurite-with-sdks-and-tools">documentation</a>. Since we are running the container on our local machine, the endpoint resolves to</p><pre>http://127.0.0.1:&lt;port&gt;/devstoreaccount1</pre><p>In this demo we are going to use the package spring-cloud-azure-starter-storage, in order to configure it, we will provide a dedicated stage <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/resources/application-azurite.yaml"><strong>application-azurite.yaml</strong></a> containing the needed configuration data for the blob storage:</p><pre>spring:<br>  cloud:<br>    azure:<br>      storage:<br>        blob:<br>          account-name: devstoreaccount1<br>          endpoint: http://127.0.0.1:10000/devstoreaccount1<br>          account-key: &quot;Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==&quot;<br>          # this is a public documented key for testing purposes with azurite, see https://learn.microsoft.com/de-de/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cblob-storage#connect-to-azurite-with-sdks-and-tools</pre><p>Don’t mind to check in the account-key. Since it is a well known public <em>secret</em>, even Github security won’t complain.</p><p>The spring-cloud-azure-starter-storage lib will automagically setup a BlobServiceClient which will be injected in our service class <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/kotlin/com/github/ralfstuckert/springazuritedemo/AzureBlobStorage.kt"><strong>AzureBlobStorage</strong></a>. Our demo application uses this class to upload a blob to the storage.</p><blockquote>Be aware that this demo is stupid simple: no timeout, retry handling etc., it is stripped down to the bare bones. Don’t do this at work ;-)</blockquote><pre>@Service<br>class AzureBlobStorage(val blobServiceClient: BlobServiceClient,<br>    @Value(&quot;\${demo.storage.blob.container}&quot;) val containerName: String) {<br><br>    private val blobContainerClient: BlobContainerClient by lazy {<br>        blobServiceClient.createBlobContainerIfNotExists(containerName) ?: blobServiceClient.getBlobContainerClient(<br>            containerName<br>        )<br>    }<br><br>    private fun getBlobClient(blobName: String): BlobClient {<br>        return blobContainerClient.getBlobClient(blobName);<br>    }<br><br>    fun updateBlob(blobName: String, byteArray: ByteArray) =<br>        getBlobClient(blobName).upload(BinaryData.fromBytes(byteArray), true)<br><br>    fun downloadBlob(blobName: String): ByteArray = <br>            getBlobClient(blobName).downloadContent().toBytes()<br>  ...<br>}<br><br><br><br>@Component<br>class StorageAccessDemo(val blobStorage: AzureBlobStorage,<br>...<br>    fun blobStorage() {<br>        val blobName = &quot;testblob&quot;<br>        logger.info(&quot;creating blob &#39;$blobName&#39;&quot;)<br>        blobStorage.updateBlob(blobName, &quot;Here we go&quot;.toByteArray(Charsets.UTF_8))<br><br>        logger.info(&quot;reading blob &#39;$blobName&#39;&quot;)<br>        val content = blobStorage.downloadBlob(blobName).toString(Charsets.UTF_8)<br>        logger.info(&quot;content is: $content&quot;)<br>    }</pre><p>If we run the demo we will get the following log output</p><pre>StorageAccessDemo: creating blob &#39;testblob&#39;<br>StorageAccessDemo: reading blob &#39;testblob&#39;<br>StorageAccessDemo: content is: Here we go</pre><h3>Azure Storage Explorer</h3><p>Ok, log output is quite fine, but I want to see the real thing, er… blob. This is where the <a href="https://azure.microsoft.com/products/storage/storage-explorer">Azure Storage Explorer</a> enters the stage. It is neat little UI based tool that let’s you inspect and alter the content of an Azure Storage. And this works both for your real Azure Storage accounts as well as for your local Azurite instance. Just <a href="https://azure.microsoft.com/products/storage/storage-explorer">download</a> and start it, and you will be connected to your azurite instance right ahead. So let’s have look at it: in the Emulator section you will find Blob Containers, Queues and Tables of your Azurite instance. In the Blob Containers node you will find our testcontainer containing our testblob. Doubleclick on the blob will download the content, and we will find our expected content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui0tiTEiT56KPhcan7-HqA.png" /></figure><h4>Sending Messages via Storage Queues</h4><p>Our little Demo also contains a handler that receives message from a storage queue named <strong>testqueue</strong>. This is implemented using spring-cloud-azure-starter-integration-storage-queue. The configuration is quite similar to the blob config, here is an excerpt from the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/resources/application-azurite.yaml"><strong>application-auzurite.yaml</strong></a>:</p><pre>spring:<br>  cloud:<br>    azure:<br>      ...<br>        queue:<br>          account-name: devstoreaccount1<br>          endpoint: http://127.0.0.1:10001/devstoreaccount1<br>          account-key: &quot;Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==&quot;<br>          # this is a public documented key for testing purposes with azurite, see https://learn.microsoft.com/de-de/azure/storage/common/storage-use-azurite?tabs=visual-studio%2Cblob-storage#connect-to-azurite-with-sdks-and-tools<br>          queue-name: testqueue</pre><p>You can look up the configuration of Spring Integration in the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/kotlin/com/github/ralfstuckert/springazuritedemo/MessageReceiver.kt#L48-L69">Github repository</a>; let’s have a look at the <a href="https://github.com/ralfstuckert/spring-azurite-demo/blob/main/src/main/kotlin/com/github/ralfstuckert/springazuritedemo/MessageReceiver.kt#L27-L31">message handler</a>:</p><pre>@Component<br>class DemoMessageHandler() : MessageHandler {<br><br>    override fun handleMessage(message: Message&lt;*&gt;) {<br>        logger.info(&quot;New message received: &#39;${message.text()}&#39;&quot;)<br>  <br>        // checkpoint the message, aka acknowledge<br>        message.checkpoint()<br>    }</pre><p>The handler just logs the incoming message and checkpoints it (aka acknowledge). You can use the Storage Explorer to inspect the messages on the queue, and also to send and delete messages. Let’s test our message handler by sending a message to our <strong>testqueue</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtxdyczcZJsNFfEjg_dBvw.png" /></figure><p>Right after adding the message our Demo client receives the message and logs it :-)</p><pre>DemoMessageHandler: New message received: &#39;Hi there, anybody listening?&#39;</pre><p>So the Storage Explorer comes quite handy when you have to deal with Blob-, Queue- and TableStorage, be it locally on Azurite or in the real cloud, just give it a try.</p><h3>Conclusion</h3><p>So this first part gave you a brief introduction on how easy it is to use <a href="https://learn.microsoft.com/azure/storage/common/storage-use-azurite">Azurite</a> as a local replacement for Azure Cloud Storage for development. The <a href="https://azure.microsoft.com/products/storage/storage-explorer">Azure Storage Explorer</a> is neat tool that helps you to inspect and manipulate the storage — both Azurite and Azure Cloud — in order to interact with your application. In the <a href="https://medium.com/@ralf.stuckert/azure-storage-development-with-azurite-part-ii-testing-493dbf6ea0de">next part</a> we will use testcontainers for writing Unit tests for our Demo application.</p><blockquote>In terms of long-term durable storage, the human mind, paradoxically, is pretty good, but it’s very fragile.<br><a href="https://de.wikipedia.org/wiki/Jonathan_Nolan">Jonathan Nolan</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cfc502ab0f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Coroutines — Update 1.6.0]]></title>
            <link>https://medium.com/@ralf.stuckert/testing-coroutines-update-1-6-0-701d53546683?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/701d53546683</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 08:31:03 GMT</pubDate>
            <atom:updated>2022-01-03T09:28:09.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Coroutines — Update 1.6.0</h3><p>About two years ago I wrote some <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">articles describing the Kotlin Coroutines Testing module</a>. With the recent <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/1.6.0/kotlinx-coroutines-test">1.6.0 release</a> things changed significantly, so it’s time for an update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0c-ony4voXhJE9h0" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleria?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building Blocks</h3><p>The building blocks of the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/1.6.0/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module have changed a bit. You may still use the old API, but those functions are deprecated and subject to vanish in a future release. The TestCoroutineExceptionHandler has been dropped without replacement; pause/resume dispatcher has been replaced by dedicated dispatcher implementations, and virtual time control has been moved to a central scheduler. If you have to port your existing code to the new API, I recommend reading the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/1.6.0/kotlinx-coroutines-test/MIGRATION.md">migration steps</a>. But let’s take this step by step.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-scheduler/index.html">TestCoroutineScheduler</a></h4><p>The scheduler controls the execution order of coroutines and implements the concept of virtual time used for skipping delays. This is a major change to the previous version of the API, where the virtual time was part of the (now deprecated) TestCoroutineDispatcher. The scheduler may be shared by multiple TestDispatchers, so execution order and time control is based on one central entity.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-dispatcher/index.html">TestDispatcher</a></h4><p>The actual dispatcher used to execute coroutines in tests. It is based on a scheduler which controls time and execution order. You may pass an existing scheduler, otherwise a new one is created. You may now use multiple TestDispatchers in a test, but be aware that they must all share one scheduler.</p><p>There are two implementations of the TestDispatcher: the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-standard-test-dispatcher.html">StandardTestDispatcher</a> and the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-unconfined-test-dispatcher.html">UnconfinedTestDispatcher</a>. The StandardTestDispatcher does <strong>not</strong> run child coroutines right away (FKA <em>paused</em>), where the UnconfinedTestDispatcher executes them eagerly.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-scope/index.html">TestScope</a></h4><p>A CoroutinesScope that integrates with the other building blocks and provides access to the TestCoroutineScheduler.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/run-test.html">runTest</a></h4><p>This function replaces runBlockingTest and runs a code block providing a TestScope, automatically skipping delays (via the TestCoroutineScheduler), and handles uncaught exceptions.</p><h3>Multiplatform Support</h3><p>kotlinx-coroutines-test became a multiplatform library in version 1.6.0, and is usable from Kotlin/JVM, Kotlin/JS, and Kotlin/Native. The only requirement is that you immediately return the result of runTest():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/632165e3b761b8aec623b9b96d80dd29/href">https://medium.com/media/632165e3b761b8aec623b9b96d80dd29/href</a></iframe><p>The reason for that is the return type runTest(...): TestResult . On JVM the actual implementation is Unit, but on Kotlin/JS it is a Promise that must be handled by the test framework. So if you want it to work on all platforms, make sure to return the TestResult immediately.</p><h3>Standard- and UnconfinedDispatcher</h3><p>In the <em>old</em> API child coroutines have been executed eagerly until the first suspension point. If this behavior was unwanted, you could change it by pausing and resuming the dispatcher. This was meant to be comfortable, but was not quite intentional in some cases. In order to provide clean semantics, this has been changed by providing two separate TestDispatcher implementations. By default, runTest() provides a StandardTestDispatcher, which does not execute child coroutines right away, let’s see this by example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b59d6844bd8f15d30947e2b1987e931/href">https://medium.com/media/8b59d6844bd8f15d30947e2b1987e931/href</a></iframe><p>So in order to execute the child coroutine, you either have to join the job, yield execution (to the child coroutine), or use runCurrent() or advanceUntilIdle() which triggers the scheduler to execute pending coroutines.</p><p>This makes the execution order quite explicit and comprehensible, and that’s why it is used by default. If this behavior is not desired, you may use an UnconfinedTestDispatcher as an alternative:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db08156a88529a7ec039d745a5e890da/href">https://medium.com/media/db08156a88529a7ec039d745a5e890da/href</a></iframe><p>That’s a lot shorter. But be aware, that eager execution stops at the first suspension point in the child coroutine. Also the unconfined dispatcher won’t help you much, if the child coroutine is started lazily:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c731958c1f1cf56347bd89de37e1622/href">https://medium.com/media/6c731958c1f1cf56347bd89de37e1622/href</a></iframe><h3>Behavior of advancing time changed</h3><p>Time control has been moved from the test dispatcher to the TestCoroutineScheduler. From a usage perspective, things do not seem to have changed at all:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4971810acdffd80b77ce3bfc7cf3e4de/href">https://medium.com/media/4971810acdffd80b77ce3bfc7cf3e4de/href</a></iframe><p>So the TestScope still provides the property currentTime and the functions advanceTimeBy(), advanceUntilIdle() and runCurrent() for you, but instead of delegating to the dispatcher, they now delegate to the TestCoroutineScheduler , and here comes the catch: the behavior of advancing time in the scheduler is slightly different now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c2aa9e077d4b251a4542f4d4842aba/href">https://medium.com/media/b3c2aa9e077d4b251a4542f4d4842aba/href</a></iframe><p>Before version 1.6.0, advanceTimBy(n) would have run a task scheduled at currentTime + n, but now it will stop just before executing any task starting at the next millisecond. So now you have to either call runCurrent() or advance time by another ms. This means if we had called advanceTimeBy(1001), the task would have been executed right away.</p><h3>Sharing the Scheduler with multiple Dispatchers</h3><p>Extracting time and execution control to some central scheduler entity has its benefits: you can now use multiple test dispatchers that share the scheduler, which allow you to control execution order. So you may now use even different dispatchers like e.g. both Standard and Unconfined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1f9979999384f551458eefdc619fb1/href">https://medium.com/media/1f1f9979999384f551458eefdc619fb1/href</a></iframe><pre>starting<br>1<br>unconfined is already started, runCurrent() will start standard<br>2<br>advanceTimeBy(n) will not run task scheduled at currentTime + n …<br>… but runCurrent() will:<br>3<br>runTest() will auto-advance all pending tasks at the end<br>4</pre><h3>Main Dispatcher</h3><p>For dealing with UI frameworks there is a Main dispatcher which usually works using a dedicated UI-Thread. In order to write tests for UI code, there was already some support by using Dispatchers.setMain(testDispatcher) (for more information read my <a href="https://medium.com/@ralf.stuckert/testing-coroutines-dispatchers-956969cfd374">previous article on that topic</a>). The pain with that solution was, that you had to use the dispatcher from the test scope, which proved to be inconvenient.</p><p>This has been eased up a lot: the TestDispatcher implementations (both standard and unconfined) now check if there is a TestMainDispatcher already in charge, and — if so — share the existing scheduler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fda73fd753b7de6e6dbcd2afaccc111/href">https://medium.com/media/6fda73fd753b7de6e6dbcd2afaccc111/href</a></iframe><p>So you may now easily set up your own Main TestDispatcher first. runTest() will create its own ( Standard) TestDispatcher , but it is using the existing scheduler from the TestMainDispatcher. This strips the pattern for tests involving the Main dispatcher down to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6555b0f68c148051d7e16578d9762375/href">https://medium.com/media/6555b0f68c148051d7e16578d9762375/href</a></iframe><p>So this was a brief description of the changes in the kotlinx-coroutines-test<a href="https://github.com/Kotlin/kotlinx.coroutines/tree/1.6.0/kotlinx-coroutines-test">1.6.0 release</a>. Over the next few weeks I will update the <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">existing articles</a> and <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">examples</a> in order to provide some more details on the new API, stay tuned.</p><blockquote><em>Because things are the way they are, <br>things will not stay the way they are.</em><br>Bertolt<strong> </strong>Brecht</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=701d53546683" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Coroutines — Remainder]]></title>
            <link>https://medium.com/@ralf.stuckert/testing-coroutines-remainder-f06954cdc95e?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06954cdc95e</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[coroutine-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 13:56:27 GMT</pubDate>
            <atom:updated>2022-01-03T09:04:37.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Coroutines — Remainder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FKOcip3UU3AOdSfR" /><figcaption>Photo by <a href="https://unsplash.com/@kotagauni_srinivas?utm_source=medium&amp;utm_medium=referral">Kotagauni Srinivas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the last part of the series on the testing coroutines with the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module, we will have a look at remaining topics like exception handling, pausing the dispatcher and some more stuff.</p><blockquote>Update: This article describes the old API. With 1.6.0 significant changes has been introduced which are described <a href="https://medium.com/@ralf.stuckert/testing-coroutines-update-1-6-0-701d53546683">here</a>. Over the next few weeks I will update this article and the examples in order to provide some more details on the new API, stay tuned.</blockquote><h3>Exception Handling</h3><p>If we want to test for exceptions in coroutines we could do so using the good old runBlocking():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907b28c8707a92ad9c19299982039a16/href">https://medium.com/media/907b28c8707a92ad9c19299982039a16/href</a></iframe><p>This works since runBlocking() rethrows the first occurring exception if no one cares for it. An alternative is to provide a dedicated CoroutineExceptionHandler in the context, which will be called on every rising exception. The runBlockingTest() function adds a TestCoroutineExceptionHandler to the context to do so. This handler also throws the first occurring exception on cleanup, but also allows to inspect all exceptions during the test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c6948dfc063b82d93447fe16f2cc89d/href">https://medium.com/media/1c6948dfc063b82d93447fe16f2cc89d/href</a></iframe><p>So this might be quite helpful in some cases. But it also may have some unexpected effects you should be aware of. A SupervisorScope is usually used if you do NOT want the supervising scope to fail, if one of the children fails. So let&#39;s see the following example, would you expect it to succeed?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c36b48226df1d57635acf9de25c31a20/href">https://medium.com/media/c36b48226df1d57635acf9de25c31a20/href</a></iframe><p>Nope, it fails. This is due the exception handler provided by runBlockingTest() which is passed to the supervisor scope. It handles all exceptions and rethrows it. If you use runBlocking() it would run right through.</p><p>So what if I do want to make use of all those goodies of runBlockingTest() without having a handler throwing exceptions? You could provide a custom handler that either does nothing at all, or <a href="https://github.com/ralfstuckert/kotlin-coroutines-test/blob/master/src/test/kotlin/coroutines/ExceptionHandler.kt">one that just collects all exceptions but does not rethrow</a>. This has the benefit that you can still analyze exceptions in your test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f3c126a56f0a77352deff2bfad48fa/href">https://medium.com/media/f0f3c126a56f0a77352deff2bfad48fa/href</a></iframe><h3>Pausing the Dispatcher</h3><p>As explained in the <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">first part</a>, the TestCoroutineDispatcher executes new coroutines immediately like they where started in mode <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-u-n-d-i-s-p-a-t-c-h-e-d.html">UNDISPATCHED</a>. This behaviour can be changed by pausing the dispatcher, see the following example. Be aware that these example do not make any sense and are solely intended to demonstrate order of execution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7254eb3d9e38ede7c5d981ac44088742/href">https://medium.com/media/7254eb3d9e38ede7c5d981ac44088742/href</a></iframe><p>Due to the call to pauseDispatcher(), the launched coroutine is NOT executed immediately, that&#39;s why state is still 0. Calling runCurrent() makes the dispatcher forward all coroutines up the current virtual time, so it proceeds up to the delay(1000) and therefore state == 2. To proceed we could either advance time (by 1000), or advanceUntilIdle() to run right through.</p><p>To complement pauseDispatcher() there is also a resumeDispatcher(). This switches execution back to immediate mode, but also advances all coroutines until idle. See the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/facbe6e883eabc7b6d0faf8720f2f6ce/href">https://medium.com/media/facbe6e883eabc7b6d0faf8720f2f6ce/href</a></iframe><p>To complete this, there is also a pauseDispatcher()variant that executes a given block of code. After the block is executed, it also resumes the dispatcher automatically:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a82acb33f6357fc7b3dc51a7c89b8e7b/href">https://medium.com/media/a82acb33f6357fc7b3dc51a7c89b8e7b/href</a></iframe><h3>Detecting Unrelated Jobs</h3><p>The TestCoroutineScope resp. runBlockingTest() is quite dependent on the TestCorouineDispatcher to make time control work properly. But it has some built in feature in order to detect misusage. Let&#39;s recap our dispatcher provider example from <a href="https://medium.com/@ralf.stuckert/testing-coroutines-dispatchers-956969cfd374">part 3</a>. We have a function loadUserIOthat uses the io dispatcher from the DispatcherProvider…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8babb2db057ee37bdf52bad3a4547ca7/href">https://medium.com/media/8babb2db057ee37bdf52bad3a4547ca7/href</a></iframe><p>… and the following test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5bf75c5f24d9ba1538275c13dff5a2/href">https://medium.com/media/eb5bf75c5f24d9ba1538275c13dff5a2/href</a></iframe><p>If you run this test, you will get:</p><pre><em>java.lang.IllegalStateException: This job has not completed yet</em></pre><p>Why is that? Ooops, we accidently used runBlockingTest() instead ofrunBlockingTestProvided(). So the test dispatcher will not be passed through the provider, but the original Dispatcher.IO is used. If we run the test, it will automatically advance until idle. But since we are not using the test dispatcher, it will not advance our coroutine :-(</p><p>Luckily runBlockingTest() has a safety belt: it counts all jobs before and after test execution. If there is a difference, it complains with the exception you saw above, and therefore gives you hint that something is wrong with your test :-)</p><p>That’s it, we’re done. There are quite a lot things you can do with the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module, so give it a try. Be aware that the API is still experimental, so things are subject to change. You will find all examples and the utility functions in the <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">accompanying git repository</a>.</p><blockquote>You’re damned if you do and <br>you’re damned if you don’t. <br><em>Bart Simpson</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06954cdc95e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Coroutines — Dispatchers]]></title>
            <link>https://medium.com/@ralf.stuckert/testing-coroutines-dispatchers-956969cfd374?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/956969cfd374</guid>
            <category><![CDATA[coroutine-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 12:04:06 GMT</pubDate>
            <atom:updated>2022-01-03T09:03:18.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Coroutines — Dispatchers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odaZVruLyWliZMSGVr3h9A.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/dmpcreate-5424877/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2332239">dmpcreate</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2332239">Pixabay</a></figcaption></figure><p>In <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">part one</a> and <a href="https://medium.com/@ralf.stuckert/testing-coroutines-timeout-36c22db1b06a">two</a> of this series we saw how to make use of the time control features of the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module. In this part you will see how to test code that utilizes a dedicated dispatcher.</p><blockquote>Update: This article describes the old API. With 1.6.0 significant changes has been introduced which are described <a href="https://medium.com/@ralf.stuckert/testing-coroutines-update-1-6-0-701d53546683">here</a>. Over the next few weeks I will update this article and the examples in order to provide some more details on the new API, stay tuned.</blockquote><h3>Main Dispatcher</h3><p>UI code like e.g. Android, Swing, JavaFX is executed by a dedicated UI-Thread. When using coroutines you have to use the Main dispatcher for that purpose. But how do we test this code? We could integrate a dedicated platform main dispatcher in our tests, but that is not always feasible. Moreover, those neat time control features introduced in the first two parts would not be accessible. Luckily, the coroutine test module provides functionality to fill in this gap. To demonstrate this, we will introduce a function waitForUserConfirm() that is supposed to be UI code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11c421c304fbb72cc7a6f75346dca3a2/href">https://medium.com/media/11c421c304fbb72cc7a6f75346dca3a2/href</a></iframe><p>In order to call it from anywhere in our code — where anywhere means: regardless of the current dispatcher — we have a function confirmDone() that makes sure that the UI code is executed on the Main dispatcher:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5123d49008ecd198844a2c5d4e8b924/href">https://medium.com/media/f5123d49008ecd198844a2c5d4e8b924/href</a></iframe><p>Now let us write some that is intended to test the confirmDone() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d72da975598a9ff81c60ee81d671619e/href">https://medium.com/media/d72da975598a9ff81c60ee81d671619e/href</a></iframe><p>We set up our UI mock to delay a bit (our user is not the fastest ;-) and return OK. Run the test: As already said, if we do not provide any main dispatcher this test will complain:</p><pre>java.lang.IllegalStateException: Module with the Main dispatcher is missing. <br>Add dependency providing the Main dispatcher, e.g. &#39;kotlinx-coroutines-android&#39; <br>and ensure it has the same version as &#39;kotlinx-coroutines-core&#39;</pre><p>To fix this, we will use the setMain() function which allows to set our <em>own</em> dispatcher as main. In order to benefit from all goodies we will use the TestCoroutineDispatcherprovided by runBlockingTest():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c83426e853408e8fbbfdd1b37ea77b2d/href">https://medium.com/media/c83426e853408e8fbbfdd1b37ea77b2d/href</a></iframe><p>Now our test becomes green. In case you are wondering where that testDispatcher is coming from: this is a <a href="https://github.com/ralfstuckert/kotlin-coroutines-test/blob/master/src/test/kotlin/coroutines/TestCoroutinesExt.kt">tiny custom helper function</a>, hopefully there will something &quot;official&quot; soon, see <a href="https://github.com/Kotlin/kotlinx.coroutines/issues/1609">issue 1609</a>.</p><h4>Main Dispatcher JUnit Extension</h4><p>To ease the handling of using a test dispatcher for main, you could also use a JUnit rule resp. extension. Here is a <a href="https://github.com/ralfstuckert/kotlin-coroutines-test/blob/master/src/test/kotlin/coroutines/MainDispatcherExtension.kt">variant of a JUnit 5 extension</a> that creates a TestCoroutineDispatcher for each test, sets it as the main dispatcher, and provides it as a parameter for the test. You have to use this dispatcher either by passing it as a context to runBlockingTest(), or call runBlockingTest() on the dispatcher (which is effectively the same thing):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1407352b21eda158768221995231616/href">https://medium.com/media/c1407352b21eda158768221995231616/href</a></iframe><h3>Other Dispatchers</h3><p>So this works well for the Main dispatcher. What about the other ones, like e.g. Default or IO? Let&#39;s do this by example: we will take our already known UserService that loads a user from e.g. a database. In order to make sure that this is done via IO dispatcher, we have a functionloadUserIO():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d8baa6b7e438699dc14af8d21e2ab95/href">https://medium.com/media/6d8baa6b7e438699dc14af8d21e2ab95/href</a></iframe><p>We could easily write a test like we did before, but how can we inject our test dispatcher? Is there a setIO() function? Nope. Maybe there will be one in future releases (see <a href="https://github.com/Kotlin/kotlinx.coroutines/issues/1365">issue 1365</a>), but not at the time of this writing.</p><p>A common approach is to inject a DispatcherProvider, an interface that abstracts the direct usage of dispatchers. To do so, we have to change our loadUserIO() as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683a8b71ec2a12f6a3e5c3a2f5222c32/href">https://medium.com/media/683a8b71ec2a12f6a3e5c3a2f5222c32/href</a></iframe><p>Now for production code, we have to use a provider that utilizes the <em>real</em> dispatchers, but we can inject the test dispatcher in our unit tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d7f360a64361951218a56dc59b1aad/href">https://medium.com/media/13d7f360a64361951218a56dc59b1aad/href</a></iframe><p>So this TestDispatcherProvider implements the DispatcherProvider interface by always providing the given (test-) dispatcher for main, io, etc. Since this idea is widespread, there are already some libraries out there doing the job. I&#39;m using <a href="https://github.com/RBusarow/Dispatch">this neat library</a> here. Besides providing a production and test dispatcher provider, it can implicitly provide the DispatcherProvider in the coroutine context, and has some extension functions to access it. The advantage is, that you do not have to alter your signature in order to pass the provider, which eases migration from direct usage of the Dispatchers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/152bcb1a07a8849f1c8164cef407a50d/href">https://medium.com/media/152bcb1a07a8849f1c8164cef407a50d/href</a></iframe><p>But how is the provider injected into the coroutine context? For production code you don’t have to do anything. If you access the provider, and there is none yet, the lib will instantiate the default provider that simply provides the orginal dispatchers, like you were using e.g. Dispatchers.IOdirectly. For testing it has the convenience function runBlockingTestProvided(): an extension of the original runBlockingTest() which automatically adds the TestDispatcherProvider to the context of the test scope:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4262435d0d9cdee3c3c6a420c101ffc/href">https://medium.com/media/f4262435d0d9cdee3c3c6a420c101ffc/href</a></iframe><p>That’s it for today, <a href="https://medium.com/@ralf.stuckert/testing-coroutines-remainder-f06954cdc95e">the last part</a> will be on pausing the dispatcher and handling exceptions. As already mentioned, you will find all example in the <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">accompanying git repository</a>.</p><blockquote>Being a Dispatcher means: <br>you will cry a lot, you will laugh a lot.<br><em>Anonymous</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956969cfd374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Coroutines — Timeout]]></title>
            <link>https://medium.com/@ralf.stuckert/testing-coroutines-timeout-36c22db1b06a?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c22db1b06a</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine-testing]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 15:22:39 GMT</pubDate>
            <atom:updated>2022-01-03T09:02:39.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Coroutines — Timeout</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czToAOkaxIA567-NVYcqPw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/tookapic-1386459/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=932693">tookapic</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=932693">Pixabay</a></figcaption></figure><p>The <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">first part</a> of this series provided you an introduction to the building blocks of the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module, and gave you some examples on eager execution and virtual time. In this second part we will have a look at testing timeouts.</p><blockquote>Update: This article describes the old API. With 1.6.0 significant changes has been introduced which are described <a href="https://medium.com/@ralf.stuckert/testing-coroutines-update-1-6-0-701d53546683">here</a>. Over the next few weeks I will update this article and the examples in order to provide some more details on the new API, stay tuned.</blockquote><p>We want a software system to feel responsive to the user, meaning a system should respond in a given time, either with the result or a failure. Since systems usually interact with other systems — be it a server, a database or whatever — we do not want to wait forever for a response. A common technique to solve this problem is using timeouts: If the operation does not respond in a given time, we will raise a timeout failure.</p><p>Kotlin coroutines already provides a function <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-timeout.html">withTimeout()</a> that helps you implement that. Let&#39;s do this by example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/401eaa08ccead5b8fe9cffd8751834de/href">https://medium.com/media/401eaa08ccead5b8fe9cffd8751834de/href</a></iframe><p>We have UserService that loads User from a remote system, so this operation might take a while. This service is injected into the<br>suspendable loadUser() function which wraps the access to the service using withTimeout().</p><p>Now we will write some test that will check our timeout behaviour. Let us start with the trivial success case, where the service responds immediately. In order to mock the UserService we will use the <a href="https://mockk.io/">MockK</a> library (if you haven&#39;t used it yet, give it a try):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/845c8469baa6e17937c526314982c2dd/href">https://medium.com/media/845c8469baa6e17937c526314982c2dd/href</a></iframe><p>So what are we doing here: we create a mock for the UserService and set it up to return our prebuilt user on every load call (coEvery and coAnswer are variants meant to deal with suspendable functions). Then we just check if the returned user is the one we set up in our mock.</p><p>Now let us write a test that checks that loadUser() fails after the given timeout. This is quite easy due to the virtual time implemented by the TestCoroutineDispatcher which gives us explicit control:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c41b0958b0945edecbb856ad710ed5/href">https://medium.com/media/d4c41b0958b0945edecbb856ad710ed5/href</a></iframe><p>So what did we do here? We simply let our mock delay for 30 seconds. In this case we expect a TimeoutCancellationException to occur. As already mentioned in the <a href="https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599">first part</a>, virtual time is reliable. So we can reliably test the boundaries of our timeout by expecting success with a delay of 29.999ms:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/effc0ff0a20feca11feed2a92c4a9453/href">https://medium.com/media/effc0ff0a20feca11feed2a92c4a9453/href</a></iframe><p>By now our function under test was suspendable. Now let’s deal with a function that starts a new coroutine using async:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/778a1bbcd8b87e0676bc9c001fd65050/href">https://medium.com/media/778a1bbcd8b87e0676bc9c001fd65050/href</a></iframe><p>Testing this is straight forward like we did before. Just call await to complete the deferred:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e71f5738489f4904897a5f5bc25b0d24/href">https://medium.com/media/e71f5738489f4904897a5f5bc25b0d24/href</a></iframe><p>If you’re wondering where this coAssertThrows() function comes from: this is <a href="https://github.com/ralfstuckert/kotlin-coroutines-test/blob/master/src/test/kotlin/coroutines/Asserts.kt">a custom variant</a> of the standard assertThrows() that is capable of dealing with suspendend functions. Alas, suspendable functions differs from regular functions, read Roman Elisarov&#39;s explanation on why the suspend modifier <a href="https://medium.com/@elizarov/how-do-you-color-your-functions-a6bb423d936d">colors functions</a> in Kotlin.</p><p>That’s it so far, <a href="https://medium.com/@ralf.stuckert/testing-coroutines-dispatchers-956969cfd374">the next part</a> will be on dealing with dispatchers. You will find all examples in the <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">accompanying git repository</a>.</p><blockquote>Why do we never have time to do it right, <br>but always have time to do it over? <br><em>Murphy’s Law</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c22db1b06a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Coroutines — Introduction]]></title>
            <link>https://medium.com/@ralf.stuckert/testing-coroutines-introduction-4ab6733c7599?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab6733c7599</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Wed, 11 Mar 2020 12:13:11 GMT</pubDate>
            <atom:updated>2022-01-03T09:01:22.644Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Coroutines — Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_teORbR4pjUAwo_-" /><figcaption>Photo by <a href="https://unsplash.com/@taylor_smith?utm_source=medium&amp;utm_medium=referral">Taylor Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the first part of my little series on testing coroutines, where we will explore the capabilities of the <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module. All examples (and some utility functions) are <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">provided in a Git repository</a>, so give it a try. This first part will introduce the building blocks of the module, and give some examples on eager execution and virtual time.</p><blockquote>Update: This article describes the old API. With 1.6.0 significant changes has been introduced which are described <a href="https://medium.com/@ralf.stuckert/testing-coroutines-update-1-6-0-701d53546683">here</a>. Over the next few weeks I will update this article and the examples in order to provide some more details on the new API, stay tuned.</blockquote><h3>Building Blocks</h3><p>The <a href="https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test">kotlinx-coroutines-test</a> module consists of four ingredients: The TestCoroutineDispatcher, a TestCoroutineExceptionHandler, the TestCoroutineScopeand finally the runBlockingTest() function. Let&#39;s take them step by step.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-dispatcher/">TestCoroutineDispatcher</a></h4><p>In contrast to other dispatchers, this one executes new coroutines immediately like they where started in mode <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-u-n-d-i-s-p-a-t-c-h-e-d.html">UNDISPATCHED</a>. This eases the handling in tests a bit. But you can change this behaviour, either by providing a dedicated start mode, or by pausing the dispatchers.</p><p>Another important point is, that it is up to a dispatcher to implement the concept of time on which scheduling and delay is based on. The <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-dispatcher/">TestCoroutineDispatcher</a>implements a virtual time and gives you fine grained control on it. This allows to write robust time based tests.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-exception-handler/">TestCoroutineExceptionHandler</a></h4><p>A <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/">CoroutineContext</a> may contain a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-exception-handler/index.html">CoroutineExceptionHandler</a> which is comparable to the uncaught exception handler on threads, and is intended to handle all exceptions that arise in a coroutine. This implementation captures and collects all exceptions, so they can be inspected in tests, and rethrows the first one on cleanup.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-test-coroutine-scope/">TestCoroutineScope</a></h4><p>This scope provides a TestCoroutineDispatcher and TestCoroutineExceptionHandler by default, if none is already given in the context. It also provides access to the the time controlling functions like advanceTime... and the uncaughtExceptions by delegating them to the TestCoroutineDispatcher resp. TestCoroutineExceptionHandler.</p><h4><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/run-blocking-test.html">runBlockingTest</a></h4><p>This variant of runBlocking() ties everything up and provides you a TestCoroutineScope and therefore a TestCoroutineDispatcher and TestCoroutineExceptionHandler. It <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-delay-controller/advance-until-idle.html">advances time</a> of the test dispatcher until idle, which effectively makes sure that everything in the test block is run. It also checks for misusage by counting the active jobs before and after the test.</p><h3>Eager Execution</h3><p>As already told the TestCoroutineDispatcher executes coroutines eagerly, means there is no need to e.g. join a job. For comparison let&#39;s first see the <em>old</em> way. Be aware that these example do not make any sense and are solely intended to demonstrate order of execution ;-)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7057fe1e9c26309431e999e61e2f2bfa/href">https://medium.com/media/7057fe1e9c26309431e999e61e2f2bfa/href</a></iframe><p>Now the same scenario with a test dispatcher provided by runBlockingTest(). No need to join, and therefore no need for the job reference. This makes it a bit more readable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b1d9cf571f2a3d9cda1351deeed6d8e/href">https://medium.com/media/5b1d9cf571f2a3d9cda1351deeed6d8e/href</a></iframe><p>A remarkable thing here is that the launched coroutine will be executed immediately, but on suspension, e.g. by yield()or delay(), execution will resume after the launch block. Luckily the DelayController implemented by the test dispatcher provides a function runCurrent() that resumes the coroutine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93dd3f88062988907a9c60e720bbe72/href">https://medium.com/media/f93dd3f88062988907a9c60e720bbe72/href</a></iframe><h3>Advancing Time</h3><p>Sometimes we have to deal with delays, be it in code or e.g. for testing timeout. Waiting for those delays in test can be tedious:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f1b89c4b922b48fa75d06683fb91c84/href">https://medium.com/media/2f1b89c4b922b48fa75d06683fb91c84/href</a></iframe><p>If you run this test, it will take a bit more than 5 seconds. Now let’s do the same thing with runBlockingTest()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24013bdeba5209e5aa44b3487bbb1b38/href">https://medium.com/media/24013bdeba5209e5aa44b3487bbb1b38/href</a></iframe><p>It takes just some milliseconds to run. The reason for that is, that the TestCoroutineDispatcher implements a virtual time, and runBlockingTest() <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-delay-controller/advance-until-idle.html">auto-advances</a> time, so the test will run right through. You have even access to that virtual time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26328ec420ca8b73a9d9deb3220959c7/href">https://medium.com/media/26328ec420ca8b73a9d9deb3220959c7/href</a></iframe><p>Be aware that the eager execution of a new coroutine also suspends at a delay. As an alternative to runCurrent()you can also use the advance...() function family to forward the execution of the coroutine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f18be368942c141d3821fed4f13637b/href">https://medium.com/media/4f18be368942c141d3821fed4f13637b/href</a></iframe><p>That means even if this test executes in a couple of millis, the virtual time is quite reliable, so you can depend on it in your tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320d5f422bdcfc0f4fc9334ebe86d149/href">https://medium.com/media/320d5f422bdcfc0f4fc9334ebe86d149/href</a></iframe><p>I guess that’s enough for today, <a href="https://medium.com/@ralf.stuckert/testing-coroutines-timeout-36c22db1b06a">the next part</a> will be on testing timeout. As already mentioned, you will find all examples in the <a href="https://github.com/ralfstuckert/kotlin-coroutines-test">accompanying git repository</a>.</p><blockquote>Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.<br><em>Martin Golding</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab6733c7599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Kotlin-React — Part III]]></title>
            <link>https://medium.com/@ralf.stuckert/getting-started-with-kotlin-react-part-iii-c316573e0abb?source=rss-52a2783859a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c316573e0abb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ralf Stuckert]]></dc:creator>
            <pubDate>Mon, 28 May 2018 03:40:17 GMT</pubDate>
            <atom:updated>2018-05-28T03:40:17.305Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ralf.stuckert/getting-started-with-kotlin-react-part-ii-9dda64c9b0c8">second part</a> we have integrated some libraries like Axios and Lodash into the Giphy Search App. We have used @JsModule and generated Kotlin types to access the libraries in a more Kotlin-like, typed way. In this last part, we will use Kotlin coroutines to deal with asynchronous calls. You will find the complete <a href="https://github.com/ralfstuckert/kotlin-react-sample">source on GitHub</a>.</p><h3>Dealing with Asynchronicity</h3><p>The giphySearch() function in <a href="https://github.com/ralfstuckert/kotlin-react-sample/blob/master/src/giphy/GiphyAPI.kt">GiphyApi.kt</a> performs the search using Axios, which makes an asynchronous HTTP call. The async get() function returns a Promise, which we use to process the response by passing a (callback-) function to then(). The return value of the giphySearch() function is itself a Promise providing either the search result or a failure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8785fffeb2bf2abfdf4f8a6f5627ef4/href">https://medium.com/media/b8785fffeb2bf2abfdf4f8a6f5627ef4/href</a></iframe><p>The giphySearch() function in turn is used by the <a href="https://github.com/ralfstuckert/kotlin-react-sample/blob/master/src/app/App.kt">App</a> to start a search when a user types into the search input field. Again, we pass functions tothen() and catch() of the Promise returned by giphySearch(), which actually handle the search result resp. any errors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4caf5d11a61f7468246340817c370f2/href">https://medium.com/media/c4caf5d11a61f7468246340817c370f2/href</a></iframe><p>Promises are quite an improvement compared to the <a href="http://callbackhell.com/">callback hell</a> we had to live with, so what´s wrong with that? When it comes to deal with conditionals, people still tend to write code pyramids like with callbacks. Anyway, cascading promises still kinda obfuscate the program flow.</p><p>In Typescript and ES8 you can use <a href="https://basarat.gitbooks.io/typescript/docs/async-await.html">async-await</a> which is basically just some syntactic sugar on top of promises. But it allows to (a)wait for an asynchronous call making your code look synchronous. Let’s compare some code handling promises with then()…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d69a2a156908357c63028fe94d03ae5/href">https://medium.com/media/1d69a2a156908357c63028fe94d03ae5/href</a></iframe><p>…with a variant using async-await:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/246c9ae6b45a50ef9fea357fb767ef4e/href">https://medium.com/media/246c9ae6b45a50ef9fea357fb767ef4e/href</a></iframe><p>Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned. The value returned by an async function is automatically wrapped into a promise.</p><h3>Using Kotlin Coroutines</h3><p>Kotlin provides <a href="https://kotlinlang.org/docs/reference/coroutines.html">Coroutines</a> to deal asynchronicity. Coroutines are computations that can be <em>suspended</em> without <em>blocking a thread</em>. Read more about this in the <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md">coroutines guide</a>. In order to use coroutines in our Kotlin-React sample you need to install kotlinx-coroutines-core:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcbd18236fcc9cd11175b496dbc3a396/href">https://medium.com/media/bcbd18236fcc9cd11175b496dbc3a396/href</a></iframe><p>After that you should run the gen-idea-libs script which integrates the lib into the IntelliJ project, so you can use it in the IDE:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8219c51f077ac53bca03a4c8dd49edaa/href">https://medium.com/media/8219c51f077ac53bca03a4c8dd49edaa/href</a></iframe><p>Older versions of the script had some issues, so if you run into any failure, just add the library manually in IntelliJ in the project structure. Just add a Kotlin/JS library and set the path to the kotlinx-coroutines-core folder in the node-modules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkvQ5u91GN0elwAgh4vWVw.png" /></figure><p>Now we are ready to write a variant of the giphySearch() function based on coroutines. Since we want our function to be suspendable it starts with the keyword suspend:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71319701e406dd4f6d469c8659bf32a2/href">https://medium.com/media/71319701e406dd4f6d469c8659bf32a2/href</a></iframe><p>We simply call Axios.get(), and in the next line we can access the result just as it was sequential, synchronous code. But where does the suspension actually happen? Notice the await() function we are calling on the promise returned by Axios. This function is provided by the coroutines library and implements a suspension point that resumes when the promise is resolved:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec5752bdea313ac6a800d20d4b539f5/href">https://medium.com/media/4ec5752bdea313ac6a800d20d4b539f5/href</a></iframe><p>So there is no need to deal with then() and watch the return type of our search function: it is no longer a promise like in giphySearch()…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dda6395704a0a8df6866ed067100c0f1/href">https://medium.com/media/dda6395704a0a8df6866ed067100c0f1/href</a></iframe><p>…but directly the array of giphies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebb63c01021618e6afe25b22d7742c9b/href">https://medium.com/media/ebb63c01021618e6afe25b22d7742c9b/href</a></iframe><p>So our search itself is now suspendable; now we have to alter the code in App.kt that actually triggers the search. Let’s recap our promise based version which calls the gipyhSearch() and sets the result state in in the then() of the returned promise, resp. the error state in case of an exception:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4caf5d11a61f7468246340817c370f2/href">https://medium.com/media/c4caf5d11a61f7468246340817c370f2/href</a></iframe><p>Now we are gonna write a coroutines based version that calls giphySearchCoroutines() in our App. Suspendable functions itself can only be called by suspendable functions. So we could make this new function suspendable, and the function that calls it, and so on… But you gotta start somewhere to <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#bridging-blocking-and-non-blocking-worlds">bridge the blocking and non-blocking worlds</a>. There are several builder functions that helps you starting a new coroutine, e.g. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html">launch()</a> and <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#concurrent-using-async">async()</a>. In our example we will use async() to start a new coroutine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dd90a4968d03a28cd1534453f29529f/href">https://medium.com/media/6dd90a4968d03a28cd1534453f29529f/href</a></iframe><p>Watch the call to giphySearchCoroutines(): we directly get the result. There is no need for await or anything like that, since we are now calling a suspendable function from within a coroutine scope. We can even simply surround it with try-catch to handle errors. Once inside a coroutine you don’t have to worry about asynchronicity when calling suspendable functions. Alls these nifty little details of suspend and resume are hidden, you are using it like it was synchronous code. And best of all: whether you are writing Kotlin/JS or Kotlin/JVM code, you always apply the same metaphors to deal with asynchronicity by using coroutines.</p><p>This is the end of our tiny tour through Kotlin-React. We have created functional, stateless and stateful components, integrated JS libraries, and finally dealt with asynchronicity. Hope you enjoyed the ride.<br>Ralf</p><blockquote>Wherever possible I try to communicate asynchronously.<br><a href="https://en.wikipedia.org/wiki/Elon_Musk">Elon Musk</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c316573e0abb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>