A better interop story with JS Promises

Sep 16, 2021

As with most things in life, when you get more experienced, you improve. The bulk of my work in the past few years has been on mobile and back-end. I’m doing a lot more work on the browser lately, learning new things every day. Since my last Kotlin JS / Promises post, I discovered an interesting trick I’d like to share.

The async and await keywords (see MDN Web Docs) act as syntactic sugar on top of promises, making asynchronous code a lot easier to write and read.

And, as a lot of the standard JS APIs, Promise’s async/await is also available to Kotlin-JS developers.

1
2
3
4
5
6
7
/**
 * Awaits for completion of the promise without blocking.
 *
 * This suspending function is cancellable.
 * ...
 */
public suspend fun <T> Promise<T>.await(): T // ...

Not only do we get a nice suspend extension function, but it’s cancellable. Let’s see how we can use this in our code.

Wrapping up Firebase JS Promises with Coroutines & Flow

Apr 14, 2021
Kotlin-JS
Firebase Realtime DB

A Promise is the way you traditionally deal with asynchronous requests in the Javascript world.

With Kotlin-JS, here is how you would typically load an entry, using only the Firebase Javascript APIs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fun example(database:Database) {
    database.ref("customer")
        .child(childKey)
        .get()
        .then { snap ->
            val customer = snap.`val`().unsafeCast<Customer>()
            logI("value: %o", customer)
        }
        .catch { throwable ->
            logE("Caught error: %o", throwable)
        }
}

This works fine™. The small problem with Promises is that they are specific to Javascript. If we hope to graduate to a Kotlin Multi-Platform setup one day, we can’t rely too much on them.

Thankfully, we can use Kotlin coroutines and the Flow API to make Firebase’s callback-based APIs easier to use.

Building a Back Office with Kotlin JS & Firebase

Mar 25, 2021
Now legitimately an entrepreneur!

I’ve recently decided to invest in a small local company with a good college buddy of mine. The company rents out containers for construction & demolition waste pickups and offers a junk removal service.

Now, when my friend bought the company a couple of years back, it was a mom-and-pop shop. The company back office he inherited was a bunch of Google Sheets, involving many manual entries with a copious amount of copy-pasta.

It worked “fine”, but the company’s day-to-day administration quickly got tedious with those kinds of tools, as you can imagine. Since my primary expertise is developing software, my role in the company will be to build a better back-office.

Enter: Kotlin-JS & Firebase