Part 4: Exploring StateFlow and SharedFlow

Dawinder Singh Gill
5 min readAug 14, 2023

This story is a part of the series I have written on Flow API in Kotlin. If you are new to Kotlin Flow, I would suggest you check this series from the beginning.

.

Stories about Kotlin Flow

6 stories

.

Introduction

Join us on a journey through State Flow and Shared Flow in software development. We’ll explore their differences, strengths, challenges, and how they impact coding projects. Discover how these methodologies shape efficiency and scalability in software, and what they mean for the future of coding.

1. StateFlow

State Flow is a type of Flow in Kotlin which allows us to manage and observe changes in data. It is a hot flow, meaning it emits data regardless of whether there are active collectors or not. StateFlow needs an initial value, and when a collector starts observing, it emits that value.

Let’s examine the example code provided to understand State Flow:

val stateFlow = MutableStateFlow(0)

stateFlow.collect {
println(it)
}

// Output:
0

--

--

Dawinder Singh Gill

Expert native Android developer, skilled in Java, Kotlin, and Jetpack Compose. Adheres to best coding practices, excels in UI/UX design and app optimization.