architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[main] Migrate from LiveData to Flow

Open JoseAlcerreca opened this issue 3 years ago • 1 comments

JoseAlcerreca avatar May 11 '22 16:05 JoseAlcerreca

Why Migrate from LiveData to Flow? Coroutines-first: Flow is integrated with Kotlin coroutines.

More powerful: Offers transformations, operators, and structured concurrency.

Lifecycle-aware alternatives exist (collectAsState, flowWithLifecycle).

Unifies data and event streams under one model.

Migration Plan: Step-by-Step

  1. Replace LiveData in Repositories/ViewModels Before:

val tasks: LiveData<List<Task>> = tasksRepository.getTasks() After:

val tasks: Flow<List<Task>> = tasksRepository.getTasks() If getTasks() was returning LiveData in the repo:

// Replace: fun getTasks(): LiveData<List<Task>>

// With: fun getTasks(): Flow<List<Task>> 2. Expose Flow in ViewModel (and convert to StateFlow if needed) In ViewModel:

private val _tasks = MutableStateFlow<List<Task>>(emptyList()) val tasks: StateFlow<List<Task>> = _tasks.asStateFlow()

init { viewModelScope.launch { tasksRepository.getTasks() .collect { _tasks.value = it } } } Optional: Use .stateIn for hot flow + sharing.

val tasks = tasksRepository.getTasks() .stateIn(viewModelScope, SharingStarted.Lazily, emptyList()) 3. Update UI Layer to Collect the Flow In Activity or Fragment:

lifecycleScope.launch { viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.tasks.collect { tasks -> // update UI } } } In Jetpack Compose:

val tasks by viewModel.tasks.collectAsState() 4. Remove LiveData Imports Replace:

import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData With:

import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow Bonus: Replace LiveData Observers with Flow Collectors Before (in Fragment):

viewModel.tasks.observe(viewLifecycleOwner) { tasks -> // update UI } After:

lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.tasks.collect { // update UI } } } Summary Checklist Repository methods return Flow

ViewModel exposes StateFlow or Flow

UI layer uses collect, collectAsState(), or stateIn

Replace all LiveData usage and observers

Test process death & recomposition

VaradGupta23 avatar Jul 16 '25 04:07 VaradGupta23