0
0
Android Kotlinmobile~3 mins

Why StateFlow and SharedFlow in Android Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how StateFlow and SharedFlow make your app's data updates smooth and bug-free!

The Scenario

Imagine you are building an app where multiple parts need to know when data changes, like a shopping cart updating the item count in different screens.

Without a proper way to share these updates, you might try to manually pass data around or use callbacks everywhere.

The Problem

Manually passing data or using callbacks can get messy fast. It's easy to miss updates, cause bugs, or write repetitive code.

Also, managing the timing of updates and ensuring all parts get the latest info is tricky and error-prone.

The Solution

StateFlow and SharedFlow provide a clean, reactive way to share data updates across your app.

StateFlow holds the latest value and emits it to new subscribers automatically, perfect for UI state.

SharedFlow broadcasts events to multiple subscribers without holding a value, great for one-time events.

Before vs After
Before
fun updateCart() {
  cartCount++
  notifyAllScreens(cartCount)
}
After
val cartState = MutableStateFlow(0)
fun addItem() {
  cartState.value = cartState.value + 1
}
What It Enables

It enables smooth, reliable communication of data changes across your app without tangled code or missed updates.

Real Life Example

When a user adds an item to their cart, StateFlow instantly updates the cart icon count on every screen without extra code.

Key Takeaways

Manual data sharing is slow and error-prone.

StateFlow and SharedFlow simplify reactive data updates.

They help keep your app UI in sync effortlessly.