Android Developer Roadmap: Hiểu về LiveData, Flow và Lập trình Phản ứng trong Android

Niềm tin cần bỏ: “LiveData là cách chuẩn để đưa dữ liệu lên UI Android”. Đúng vào 2018, sai vào 2026. LiveData vẫn được hỗ trợ và vẫn hợp lý trong app XML/Java cũ, nhưng app Kotlin viết mới — nhất là app dùng Compose — lấy Flow và StateFlow làm mặc định. Bài này đi từ mô hình đó đến code chạy được, kèm ví dụ LiveData và bảy bẫy thường gặp.

Cập nhật 2026: LiveData lùi, Flow lên

  • Lifecycle 2.11.0 stable, đã hỗ trợ KMP; lifecycle-runtime-compose cung cấp collectAsStateWithLifecycle().
  • LiveData không bị deprecate, nhưng app Compose-first dùng StateFlow; LiveData còn là cầu nối cho View/Java và module cũ.
  • Compose BOM 2026.09.00 / Compose 1.12.1: recomposition đọc snapshot state, không đọc LiveData; observeAsState() chỉ là adapter.
  • kotlinx.coroutines là stack đồng thời mặc định; StateFlow và SharedFlow đã ổn định.

“Reactive” trong Android nghĩa là gì?

Lập trình phản ứng mô tả dữ liệu như luồng chảy theo thời gian; thành phần khác đăng ký để phản ứng khi có giá trị mới. Trong Android: UI là hàm của state. Bạn mô tả giao diện theo state thay vì sửa View sau mỗi lần có dữ liệu.

State đi xuống, event đi lên

Luồng một chiều: Repository, ViewModel, UI. Chiều ngược chỉ có event — bấm nút, kéo, gõ phím. ViewModel không đọc View; View không tự sửa dữ liệu. Giữ ranh giới này thì bug “UI sai sau khi xoay màn hình” biến mất, vì UI chỉ vẽ lại từ state hiện tại.

Cold và hot

Cold: producer chỉ chạy khi có collector, mỗi collector khởi động lại từ đầu. Hot: producer chạy độc lập, nhiều collector chia sẻ luồng và có thể nhận giá trị đã phát trước đó. LiveData là hot; StateFlow là hot state; SharedFlow là hot event; flow {} là cold.

LiveData: lifecycle-aware, nhưng đã hết là mặc định

LiveData là observable data holder. Điểm mạnh thật nằm ở observe(owner, observer): chỉ giao giá trị khi owner STARTED hoặc RESUMED, tự remove khi DESTROYED, phát lại giá trị cuối khi active trở lại. Nhờ ViewModel giữ nó, xoay màn hình không mất dữ liệu và không gọi lại API.

setValue() chạy trên main thread; postValue() đẩy sang main và gộp các lần gọi liên tiếp, chỉ giá trị cuối được giao. LiveData cũng không so sánh bằng: set cùng giá trị vẫn notify.

Vì sao LiveData không hợp với Compose

Compose đọc State<T> từ snapshot system. LiveData không phải nguồn snapshot, nên phải bắc cầu bằng observeAsState() (artifact runtime-livedata): thêm dependency, thêm adapter, mỗi recomposition vẫn qua observer API.

LiveData thiếu gần như mọi thứ cho pipeline: không debounce, flatMapLatest, combine, catch, retry; switchMap đổi nguồn nhưng không hủy coroutine bên trong. Không có “chưa có giá trị”: null là giá trị hợp lệ, nên Loading, Empty, Error phải nhét chung một kiểu, còn event một lần thì không biểu diễn được.

// File: ui/legacy/ProfileFragment.kt
class ProfileViewModel(private val repo: ProfileRepository) : ViewModel() {
    private val _state = MutableLiveData<ProfileUiState>(ProfileUiState.Loading)
    val state: LiveData<ProfileUiState> = _state

    fun load(userId: String) {
        viewModelScope.launch {
            _state.value = ProfileUiState.Loading
            _state.value = try {
                ProfileUiState.Content(repo.profile(userId))
            } catch (e: IOException) {
                ProfileUiState.Error("Không tải được hồ sơ")
            }
        }
    }
}

// Fragment: chỉ nhận giá trị khi view ở STARTED trở lên
viewModel.state.observe(viewLifecycleOwner) { state -> render(state) }

Code này ổn cho app View hiện có; đừng migrate hàng loạt chỉ vì “Flow mới hơn”. Nhưng nếu màn hình sắp chuyển sang Compose, viết mới bằng StateFlow ngay từ đầu rẻ hơn viết lại.

Flow: cold, chạy lại theo từng collector

Flow<T> là luồng bất đồng bộ có hủy theo scope. flow {} chỉ chạy khi có người collect, mỗi collector mới chạy lại từ đầu. Đó là tính chất, không phải hạn chế: một truy vấn nên chạy riêng cho từng subscriber.

Flow thắng LiveData ở ba điểm: operator khai báo (map, filter, debounce, combine…), exception lan truyền theo đúng coroutine, và cấu trúc hủy — collector hủy thì upstream hủy, không cần removeObserver.

Đừng block bên trong flow: Thread.sleep, runBlocking hay IO blocking làm nghẽn dispatcher; dùng hàm suspend và flowOn(Dispatchers.IO). Cold flow không giữ state: UI recompose rồi collect lại sẽ chạy lại request — đó là lý do state thuộc về ViewModel qua stateIn.

StateFlow và SharedFlow: state và event không phải một thứ

Tiêu chí StateFlow SharedFlow
Bản chất Giữ một giá trị hiện tại, luôn có Phát nhiều giá trị, không có giá trị hiện tại
Collector mới Nhận ngay giá trị hiện tại Nhận theo replayCache; mặc định 0
Giá trị trùng Bỏ qua giá trị bằng nhau Phát mọi lần emit
Dùng cho Trạng thái màn hình Event một lần hoặc broadcast

StateFlow là state: UI phải vẽ lại theo nó, nên nó luôn có giá trị, gộp khi collector chậm, bỏ giá trị trùng. SharedFlow là event: UI làm một việc đúng một lần, nên không có giá trị ban đầu và không phát lại ngoài ý muốn.

Trộn hai thứ này sinh ra hai bug quen: xoay màn hình thấy lại toast cũ (event bị coi là state), hoặc điều hướng hai lần vì hai collector cùng nhận event. Giá trị cần đọc lại khi collector mới vào là state; giá trị chỉ có nghĩa tại lúc xảy ra là event.

Operator: ít code, hành vi rõ

Operator chạy trên cold flow, trả về flow mới; không gì chạy cho đến khi collect. Năm operator dưới đây đủ cho phần lớn màn hình.

Operator Làm gì Dùng khi
map Biến đổi từng giá trị DTO sang UI model
filter Bỏ giá trị không thỏa điều kiện Lọc danh sách hoặc trạng thái
debounce Chỉ phát giá trị cuối sau khoảng lặng Ô tìm kiếm, gõ phím
flatMapLatest Map sang flow mới, hủy flow cũ Search, đổi filter thì tải lại
combine Ghép nhiều flow, phát khi một flow đổi Nhiều nguồn state cùng chi phối UI

flatMapLatest quan trọng nhất: nó hủy flow bên trong khi có giá trị mới, nên request cũ bị cancel thay vì đua ghi vào UI — đúng thứ switchMap của LiveData thiếu. API vẫn experimental, cần @OptIn(ExperimentalCoroutinesApi::class).

stateIn: biến cold flow thành state có kiểm soát

stateIn(scope, started, initialValue) chạy upstream trong scope, giữ giá trị cuối, chia sẻ cho nhiều collector. Nó là ranh giới giữa luồng dữ liệu và trạng thái màn hình: upstream vẫn khai báo, UI chỉ đọc StateFlow.

SharingStarted Hành vi Hệ quả
Eagerly Chạy ngay khi scope sống, không dừng Upstream chạy mãi, đốt pin, giữ observer vô ích
Lazily Chạy ở collector đầu, không dừng Vẫn chạy sau khi UI đã rời màn hình
WhileSubscribed(5_000) Chạy khi có subscriber, dừng sau 5 giây không còn ai Sống qua xoay màn hình, không chạy nền vô ích

Vì sao là 5 giây

Xoay màn hình làm Activity/Fragment hủy rồi tạo lại; trong khoảng đó không có subscriber. Dừng ngay thì flow khởi động lại, mất cache và có thể gọi lại API. Năm giây đủ che khoảng trống đó và lúc tắt màn hình ngắn, mà không giữ timer hay Room observer sống hàng phút.

replayExpirationMillis quyết định giữ giá trị cuối bao lâu sau khi dừng; mặc định vô hạn. Với dữ liệu nhạy cảm hoặc dễ cũ, đặt 0 để collector mới thấy Loading.

Thu thập đúng vòng đời

Vấn đề nằm ở chỗ collect, không ở Flow. Collect trong composition hoặc scope sống lâu hơn UI sẽ chạy khi màn hình đã background: tốn CPU, tốn pin, và với Room là giữ observer.

Compose: collectAsStateWithLifecycle

collectAsStateWithLifecycle() đăng ký theo LocalLifecycleOwner, dừng ở STOPPED và chạy lại ở STARTED; giá trị cuối vẫn giữ nên UI không nhấp nháy. Nó nằm trong lifecycle-runtime-compose (Lifecycle 2.11.0). collectAsState() chỉ collect đến khi composition rời cây, kể cả khi app background.

View: repeatOnLifecycle

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.state.collect { render(it) }
    }
}

repeatOnLifecycle hủy block khi xuống dưới STARTED và chạy lại khi lên. Đừng dùng launchWhenStarted: đã deprecated vì chỉ trì hoãn, không hủy collector.

Room và DataStore trả về Flow

Room 2.8.5 và DataStore 1.3.0 đều lấy Flow làm kiểu trả về chuẩn. DAO trả Flow<List<Task>> tự phát lại khi bảng bị ghi nhờ invalidation tracker. DataStore expose data: Flow<Preferences>, bạn map sang model.

// File: data/TaskRepository.kt
fun observeTasks(): Flow<List<Task>> = taskDao.observeAll()           // Room tự đẩy dữ liệu mới
val settings: Flow<Settings> = dataStore.data.map { it.toSettings() } // DataStore 1.3.0

Repository trả cold Flow; ViewModel gọi stateIn; UI không thấy DAO. Nếu chỉ đọc một lần, dùng hàm suspend và first(), đừng dựng flow chỉ để collect một giá trị.

Xử lý lỗi trong Flow

catch chỉ bắt exception từ upstream. Exception trong lambda collect (downstream) không bị bắt, và exception hủy coroutine không nên bị nuốt. Đặt catch bên trong flatMapLatest để pipeline cha còn sống và retry còn tác dụng; emit lỗi thành state thay vì im lặng.

repository.search(query)
    .retryWhen { cause, attempt ->
        val retryable = cause is IOException && attempt < 3
        if (retryable) delay(1_000L * (attempt + 1))   // backoff tuyến tính
        retryable
    }
    .catch { emit(SearchUiState.Error(it.message ?: "Lỗi không xác định")) }

retry và retryWhen là chỗ đặt backoff: chỉ retry lỗi tạm thời như IOException hay 5xx, không retry 4xx. Với UI, đừng ném exception ra khỏi ViewModel rồi bắt trong Composable; biến nó thành field trong state.

Ví dụ chạy được: tìm kiếm có debounce

ViewModel ghép query đã debounce với cờ retry, hủy request cũ bằng flatMapLatest, expose StateFlow qua stateIn.

// File: ui/search/SearchViewModel.kt
package com.example.search

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*

sealed interface SearchUiState {
    data object Loading : SearchUiState
    data class Success(val items: List<SearchItem>) : SearchUiState
    data class Error(val message: String) : SearchUiState
}

class SearchViewModel(private val repository: SearchRepository) : ViewModel() {

    private val query = MutableStateFlow("")
    private val retries = MutableStateFlow(0)

    @OptIn(ExperimentalCoroutinesApi::class)
    val uiState: StateFlow<SearchUiState> = query
        .debounce(300)
        .combine(retries) { q, attempt -> q to attempt }
        .distinctUntilChanged()
        .flatMapLatest { (q, _) ->
            repository.search(q)
                .map { items -> SearchUiState.Success(items) }
                .onStart { emit(SearchUiState.Loading) }
                .catch { emit(SearchUiState.Error(it.message ?: "Lỗi không xác định")) }
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = SearchUiState.Loading,
        )

    fun onQueryChange(value: String) { query.value = value }
    fun onRetry() { retries.update { it + 1 } }
}
// File: ui/search/SearchScreen.kt
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun SearchScreen(viewModel: SearchViewModel = viewModel()) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    var text by rememberSaveable { mutableStateOf("") }

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        OutlinedTextField(
            value = text,
            onValueChange = { text = it; viewModel.onQueryChange(it) },
            label = { Text("Tìm kiếm") },
            modifier = Modifier.fillMaxWidth(),
        )
        when (val s = state) {
            SearchUiState.Loading -> CircularProgressIndicator()
            is SearchUiState.Error -> {
                Text(s.message)
                Button(onClick = viewModel::onRetry) { Text("Thử lại") }
            }
            is SearchUiState.Success -> LazyColumn {
                items(s.items, key = { it.id }) { item -> Text(item.title) }
            }
        }
    }
}

Test Flow: runTest và Turbine

runTest chạy coroutine với virtual time: delay(300) trong debounce không làm test chậm thật. Turbine (Cash App, artifact app.cash.turbine:turbine) biến flow thành hàng đợi sự kiện để assert từng emission thay vì collect rồi sleep.

// File: test/SearchFlowTest.kt
import app.cash.turbine.test
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals

class SearchFlowTest {
    @Test
    fun `debounce chỉ phát giá trị cuối`() = runTest {
        flowOf("r", "ro", "roo").debounce(300).test {
            assertEquals("roo", awaitItem())   // "r" và "ro" bị nuốt
            awaitComplete()
        }
    }
}

Ba API đủ dùng: awaitItem(), awaitComplete(), cancelAndIgnoreRemainingEvents(). Flow không kết thúc như Room hay StateFlow thì đóng test bằng cancelAndIgnoreRemainingEvents(). ViewModel dùng viewModelScope cần đặt main dispatcher qua rule. Assert giá trị và trạng thái lỗi, đừng assert số lần emit.

Bảy bẫy thường gặp

Bẫy Cách sửa
Collect trong composition bằng LaunchedEffect hoặc collectAsState Dùng collectAsStateWithLifecycle(); với View thì repeatOnLifecycle
GlobalScope.launch { flow.collect } Scope không ai hủy thì collector sống mãi; dùng viewModelScope hoặc lifecycleScope
stateIn với SharingStarted.Eagerly Upstream chạy cả khi không ai xem; dùng WhileSubscribed(5_000)
SharedFlow có replay > 0 cho event một lần Collector mới nhận lại event cũ; để replay = 0
Blocking trong flow: Thread.sleep, runBlocking, IO trên Main Dùng hàm suspend và flowOn(Dispatchers.IO); tính toán nặng đẩy sang Dispatchers.Default
Expose MutableStateFlow ra UI UI sửa được state, phá một chiều; expose StateFlow, cập nhật qua hàm của ViewModel
Dùng LiveData trong màn hình Compose mới observeAsState() chỉ là adapter; chuyển sang StateFlow + collectAsStateWithLifecycle

Khi nào dùng cái nào

Tình huống Chọn Ghi chú
App XML/View, Java, module cũ LiveData Giữ nguyên; chỉ đổi khi chuyển sang Compose
State màn hình trong Compose StateFlow Kèm collectAsStateWithLifecycle()
Sự kiện một lần: toast, điều hướng SharedFlow replay 0 Hoặc Channel nếu chỉ một consumer
Đọc một lần rồi thôi Hàm suspend Không dựng flow chỉ để gọi first()
Nguồn Room/DataStore Cold Flow + stateIn ViewModel giữ state, UI chỉ đọc

Checklist

  • State màn hình là một StateFlow do ViewModel expose; không có MutableStateFlow lọt ra UI.
  • stateIn dùng WhileSubscribed(5_000), trừ khi có lý do rõ ràng để khác.
  • Compose collect bằng collectAsStateWithLifecycle(); View collect trong repeatOnLifecycle.
  • Không có GlobalScope, không blocking trong flow, không LaunchedEffect collect trực tiếp.
  • Event một lần nằm trên SharedFlow replay 0; có test runTest cho luồng quan trọng.

Đọc tiếp