Flow exception handling (Part 1)

No try/catch inside Flow!?

Guowei Lv

3 minute read

You may have heard that “No try/catch inside Flow” or “Only use catch() operator”. But why? Let’s explore from the beginning. Here is a very simple setup: fun main() = runBlocking { val worker = Worker() val scope = CoroutineScope(EmptyCoroutineContext) val flow = flow { emit(1) emit(2) emit(3) } scope.launch { try { flow.collect { println(worker.doWork(it)) } } catch (e: Exception) { println("Error in collect: ${e.message}") } } delay(10000) } class Worker { fun doWork(n: Int): String = if (Random.

What is a Coroutine?

What is actually a Coroutine?

Guowei Lv

2 minute read

The first question we should ask when learning Kotlin Coroutine is: what is a Coroutine after all? Let’s go back to the Thread world and ask the same question, what is a Thread? Here is code that will create a simple Thread and start it: val thread = thread { } So the answer seems obvious, a Thread is just the Thread object returned. Easy. Can we say the same in the Coroutine world?

Guowei Lv

2 minute read

The title of this episode is called “Side effects”, but in my opinion, it’s all about how to move side-effects out of the function and make the function composable. Side effects in the body of the function If there is some side-effects in the body of the function, we can move the side-effect into the return of the function, and let the caller deal with it. func computeWithEffect(_ x: Int) -> Int { let computation = x * x + 1 print("Computed (computation)") return computation } We can move the stuff to print into the return type.

Guowei

1 minute read

When I was very young, like in primary school, I got a cassette of anime songs, I was so shocked and immediately fallen in love with. It’s a collection of songs from Macross 7. To this day, I have never watched that anime, but the songs are so touching I have to post it here. I found this amazing live concert that contains all the familiar melodies: