Better Programming

Advice for programmers.

Follow publication

Member-only story

Using Kotlin Flow in Swift

Nicklas Jensen
Better Programming
Published in
5 min readMay 28, 2021

Code snippet
Photo by the author.

My team recently started developing components for our mobile applications using Kotlin Multiplatform Mobile with Jetpack Compose on Android and SwiftUI on iOS.

If you’re already familiar with Kotlin, you may know about the concept of coroutines in Kotlin that greatly simplifies threading and asynchronous programming in general. One of the key components of coroutines in Kotlin is the Flow<T> type, which is the interface all asynchronous flows in Kotlin implement. While Flow<T> is straightforward to consume in Android (and JVM targets in general), representing interfaces in Objective-C/Swift brings with it the limitations of protocols, including a lack of generic type parameters.

While exploring the limits of code sharing between Android and iOS, we faced the challenge of having to consume these asynchronous flows from Kotlin in Swift without inhibiting the ease of use in Android. During the investigation of solutions to the problem, we went through a couple of options that I will cover in this article.

TL;DR: Accommodate usage in Swift by introducing overloads for methods returning Flow<T>, which invokes callbacks while collecting the asynchronous flow in a dedicated

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Nicklas Jensen
Nicklas Jensen

Written by Nicklas Jensen

Senior Software Developer working @ Cardlay, leading our Open Source and tech writing efforts

Write a response

Implementing this was a bit of a rough experience.
Some of the gists only show a snippet (as is mentioned in the article, follow the links in the caption).

--

Even a year later this was useful to me. So thank you!

--

The definition of error.isKotlinCancellation is missing. I assumed that line can be replaced by
if error is KotlinCancellationException {
return
}

--