惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
量子位
V
Visual Studio Blog
博客园 - Franky
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
罗磊的独立博客
小众软件
小众软件
V
V2EX
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 三生石上(FineUI控件)
大猫的无限游戏
大猫的无限游戏
有赞技术团队
有赞技术团队
月光博客
月光博客
Recent Announcements
Recent Announcements
雷峰网
雷峰网
F
Fortinet All Blogs
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Fighting Your State. Reduce And Conquer It.
numq · 2026-05-14 · via DEV Community
Cover image for Stop Fighting Your State. Reduce And Conquer It.

numq

MVVM seemed simple. Then you added ten MutableStateFlow properties to your ViewModel. MVI promised purity. Then you wrote a middleware for side effects.

There’s a better way.

The Problem With MVVM

A typical ViewModel looks like this:

class ProfileViewModel : ViewModel() {
    val name = MutableStateFlow("")
    val email = MutableStateFlow("")
    val isLoading = MutableStateFlow(false)
    val error = MutableStateFlow<String?>(null)

    fun updateProfile(name: String) {
        viewModelScope.launch {
            isLoading.value = true
            try {
                profileService.update(name)
                this@ProfileViewModel.name.value = name
            } catch (e: Exception) {
                error.value = e.message
            } finally {
                isLoading.value = false
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Five mutable properties. Loading state scattered across three places. Error handling duplicated in every method. And the ViewModel doesn’t own its side effects — viewModelScope does.

The Problem With MVI

MVI fixes the state explosion by putting everything in a sealed interface:

sealed interface ProfileState {
    data object Loading : ProfileState
    data class Loaded(val name: String, val email: String) : ProfileState
    data class Error(val message: String) : ProfileState
}

Enter fullscreen mode Exit fullscreen mode

But MVI doesn’t tell you how to handle side effects. Some use middleware. Some use Channel. Some hack it with LaunchedEffect. Every project reinvents the wheel.

Reduce & Conquer

Reduce & Conquer layers

The core idea: a reducer is a pure function that returns more than just state.

data class Transition<State, Event>(
    val state: State,
    val events: List<Event> = emptyList(),
    val effects: List<Effect> = emptyList()
)

Enter fullscreen mode Exit fullscreen mode

A transition has three outputs:

  • State - the new state
  • Events - one-shot notifications (navigation, snackbar)
  • Effects - long-running or async work

Effects are first-class citizens:

sealed interface Effect {
    data class Stream<Command>(
        val key: Any,
        val flow: Flow<Command>,
        val strategy: Strategy = Strategy.Sequential,
        val fallback: (suspend (Throwable) -> Command)? = null
    ) : Effect

    data class Action<Command>(
        val key: Any,
        val fallback: (suspend (Throwable) -> Command)? = null,
        val block: suspend () -> Command
    ) : Effect

    data class Cancel(val key: Any) : Effect
}

Enter fullscreen mode Exit fullscreen mode

  • Stream - subscribes to a flow, emits commands back

  • Action - runs one async operation, emits a command

  • Cancel - cancels by key, preventing leaks

A Reducer in Practice

class ProfileReducer(
    private val profileService: ProfileService
) : Reducer<ProfileState, ProfileCommand, ProfileEvent> {

    override fun reduce(
        state: ProfileState,
        command: ProfileCommand
    ): Transition<ProfileState, ProfileEvent> = when (command) {
        is ProfileCommand.UpdateProfile -> transition(
            state.copy(isLoading = true)
        ).effect(
            action(
                key = "update_profile",
                fallback = { ProfileCommand.ProfileError(it) },
                block = {
                    profileService.update(command.name)
                    ProfileCommand.ProfileUpdated
                }
            )
        )

        is ProfileCommand.ProfileUpdated -> transition(
            state.copy(isLoading = false)
        ).event(ProfileEvent.NavigateBack)

        is ProfileCommand.ProfileError -> transition(
            state.copy(
                isLoading = false,
                error = command.throwable.message
            )
        )
    }
}

Enter fullscreen mode Exit fullscreen mode

No viewModelScope. No LaunchedEffect. No mutable properties. One pure function.

Why This Is The Benchmark

MVVM

  • State: Multiple MutableStateFlow
  • Side effects: viewModelScope.launch
  • Cancellation: Manual
  • Testing: Mock ViewModel

MVI

  • State: Single sealed class/interface
  • Side effects: Ad-hoc (middleware, Channel)
  • Cancellation: Manual
  • Testing: Mock reducer + middleware

Reduce & Conquer

  • State: Single sealed interface
  • Side effects: Built-in (Effect)
  • Cancellation: Automatic by key
  • Testing: One pure function call

Testing a reducer:

@Test
fun `update profile sets loading and fires effect`() {
    val transition = reducer.reduce(
        state = ProfileState(),
        command = ProfileCommand.UpdateProfile("Alice")
    )

    assertTrue(transition.state.isLoading)
    assertEquals(1, transition.effects.size)
    assertEquals(0, transition.events.size)
}

Enter fullscreen mode Exit fullscreen mode

One call. No coroutines. No mocks.

The Rule

State flows down. Commands flow up. Effects manage the rest.

The View sends Commands. The Reducer returns a Transition with new State, Events, and Effects. The Feature executes Effects and feeds resulting Commands back into the Reducer. That's it.

Reduce & Conquer diagram

Full implementation in the GitHub repository.