-
Notifications
You must be signed in to change notification settings - Fork 3
LiveData -> StateFlow ์ ํ ์ ์ย #730
Copy link
Copy link
Open
Labels
Description
๋ฐฐ๊ฒฝ
ํ์ฌ ํ๋ก์ ํธ์์ LiveData๋ฅผ ์ฌ์ฉํ์ฌ UI ์ํ๋ฅผ ๊ด๋ฆฌํ๊ณ ์์ต๋๋ค.
LiveData.value๋ ํญ์ nullable์ ๋ฐํํ๊ธฐ ๋๋ฌธ์, ์ด๊ธฐ๊ฐ์ ์ง์ ํ๋๋ผ๋ ์ฌ์ฉํ๋ ์ชฝ์์ ๋งค๋ฒ null ์ฒ๋ฆฌ๊ฐ ํ์ํฉ๋๋ค.
// LiveData - ์ด๊ธฐ๊ฐ์ ์คฌ๋๋ฐ๋ nullable
val state: LiveData<CoursesUiState> get() = _state
// ์ฌ์ฉํ ๋๋ง๋ค ?. ๋๋ !! ํ์
state.value?.copy(...)StateFlow๋ฅผ ์ฌ์ฉํ๋ฉด
// StateFlow - ์ด๊ธฐ๊ฐ์ด ๋ณด์ฅ๋๋ฏ๋ก non-null
private val _state = MutableStateFlow(CoursesUiState(...))
val state: StateFlow<CoursesUiState> = _state.asStateFlow()
// ๊ฐ์ ์ฝ์ ๋ null ์ฒ๋ฆฌ ๋ถํ์
val currentCourses = state.value.courses // non-null ๋ณด์ฅ์ฃผ์ ์ฐจ์ด์
1. value nullable
์ ๋ฐฐ๊ฒฝ ์น์ ์ฐธ๊ณ .
2. Lifecycle ์ธ์
LiveData๋ observe()์ LifecycleOwner๋ฅผ ๋๊ธฐ๋ฉด ์์์ ๊ตฌ๋
/ํด์ ๋ฅผ ์ฒ๋ฆฌํด์ค๋ค.
// LiveData - observe๋ง ํ๋ฉด ๋
viewModel.state.observe(this) { state -> ... }StateFlow๋ ์ง์ lifecycle-awareํ ์ฝ๋ฃจํด ์ค์ฝํ ์์์ collectํด์ผ ํ๋ค.
// StateFlow - repeatOnLifecycle์ผ๋ก ๊ฐ์ธ์ผ ํจ
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.state.collect { state -> ... }
}
}Reactions are currently unavailable