Kotlin for C# Developers – Asynchronous Programming

Series Introduction

With my recent work in Kotlin in the last few years and my continuing work in C# throughout my entire professional career, I’m often asked to compare the two languages. This sparked the creation of my latest conference session – Kotlin for C# Developers.

The next time I’m giving this talk is at NDC London – https://ndc-london.com/talk/kotlin-for-c-developers/

But I figured some blog posts on the subject would be a great tool to sit alongside the talk. The goal of this comparison is to give C# developers some easy ways to get into Kotlin without having to dive in and build something real. Start with the building blocks you know and draw comparisons to one of the coolest languages on the market.

If you prefer to just jump right into a language / platform – I would happily suggest my Pluralsight course – Building Android Apps with Kotlin: Getting Started. Take a look here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/

C# Async Await

C# has done arguably the best job at simplifying asynchronous programming for developers. We now hardly have to think about thread management, opening, closing, splitting, etc. We can just toss around some async, await, and Task and we’re basically good to go. As long as you’re using it properly all the way through your application, async asyncing all the way through, then you should easily be able to avoid lost threads, race conditions, etc.

If you’re new to async await in C#, here is a quick example of a process that sets a list of dogs entirely in the background (although done unsafely, it’s just a quick dummy sample).

public class DogAdoptionService
{
    List<AdoptableDog> dogs;

    public async Task<List<AdoptableDog>> GetAdoptableDogsAsync()
    {
        var dogJson = await new HttpClient().GetStringAsync("http://mydogservice.azurewebsites.net");
        return JsonConvert.DeserializeObject<List<AdoptableDog>>(dogJson);
    }
    public void BackgroundGet()
    {
        Task.Run(async () => dogs = await GetAdoptableDogsAsync());
    }
}

Kotlin Coroutines

Kotlin’s concept of asynchronous programming takes a different approach, but one that is just as easy to follow and use. They call it Coroutines. I know, I know, they missed an opportunity to call it Koroutines, but still…. they’re great!

class DogAdoptionService {
    var dogs: List<AdoptableDog>? = null
    fun getAdoptableDogs(): List<AdoptableDog> {
        var json = URL("http://mydogservice.azurewebsites.net").readText()
        val listType = object : TypeToken<List<AdoptableDog>>() { }.type
        return Gson().fromJson(json, listType)
    }

    fun getAdoptableDogsInBackground() {
        GlobalScope.launch {
            dogs = getAdoptableDogs()
        }
    }
}

Side note: this really isn’t the best way to make an HTTP GET request in Kotlin, but I wanted to make it as symmetrical as possible between my C# example.

In this example, we launch a new coroutine from the GlobalScope that executes the long running getAdoptableDogs() function. One thing coroutines does that is different from other simple async await style programming is making it easier to create and manage different scopes of your coroutines if you wish. Of course, you can still launch many different coroutines from GlobalScope as well as manage heavy concurrencies.

The docs on Kotlin Coroutines actually has some awesome and simplified examples so I definitely recommend checking that out.
https://kotlinlang.org/docs/reference/coroutines-overview.html

If you wanted to essentially await a coroutine from within another or from within the main thread, all you have to do is get a reference to the coroutine and call .join() on it.

Here’s how that would look in our previous example:

class DogAdoptionService {
    var dogs: List<AdoptableDog>? = null
    fun getAdoptableDogs(): List<AdoptableDog> {
        var json = URL("http://mydogservice.azurewebsites.net").readText()
        val listType = object : TypeToken<List<AdoptableDog>>() { }.type
        return Gson().fromJson(json, listType)
    }

    fun getAdoptableDogsInBackground() {
        val dogsJob = GlobalScope.launch {
            dogs = getAdoptableDogs()
        }

        dogsJob.join() // now we wait for the coroutine to finish before continuing
        system.out.println(dogs)
    }
}

I won’t bore you with tons and tons of samples of coroutines in different situations since the docs (linked above) already do an incredible job of painting different scenarios.

Conclusion

As we continue looking into Kotlin from the perspective of a C# developer, we see more parallels and similarities – especially in both of their ease of asynchronous programming! Whether it’s async await or coroutines, us as application developers can take our minds off of heavy duty thread management and more on our design patterns and implementations!

Let me know what you think in the comments or on twitter and be sure to check back for more developer updates and Kotlin and C# posts!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisement