Skip to content

Kotlin Flow

DodaTech 1 min read

In this tutorial, you'll learn about Fix Kotlin Flow Not Emitting. We cover key concepts, practical examples, and best practices.

The Problem

Flow does not emit values or the collector does not receive emissions.

Quick Fix

Use flow builder

Wrong:

val myFlow = flow {
    emit(1)
    emit(2)
} // Flow created

Output:

Correct

Right:

val myFlow = flowOf(1, 2, 3) // Simple flow

Output:

Simpler creation

Collect the flow

Wrong:

myFlow // Not collected

Output:

No emissions

Right:

myFlow.collect { value ->
    println(value)
} // Collect triggers execution

Output:

Values emitted and collected

Use proper dispatcher

Wrong:

myFlow.flowOn(Dispatchers.Default)
    .collect { /* on Main thread */ }

Output:

Blocking main thread

Right:

myFlow.flowOn(Dispatchers.Default)
    .collect { value ->
        withContext(Dispatchers.Main) { updateUI(value) }
    }

Output:

Proper dispatcher usage

Prevention

  • Use flow { } or flowOf() to create flows
  • Call collect() to trigger flow execution
  • Use flowOn() for upstream dispatcher context

Common Mistakes with flow

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does my Flow never emit?

Flow is cold and only emits when collected. Ensure collect() is called.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro