generated from AND-SOPT-ANDROID/and-sopt-android-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#13 [Feat] : 추가 State, Event, SideEffect 공통 관리를 위한 BaseViewModel 생성
- Loading branch information
1 parent
2b4fdc0
commit 1c51977
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
app/src/main/java/org/sopt/and/presentation/core/BaseViewModel.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package org.sopt.and.presentation.core | ||
|
||
import androidx.lifecycle.ViewModel | ||
import androidx.lifecycle.viewModelScope | ||
import kotlinx.coroutines.flow.MutableSharedFlow | ||
import kotlinx.coroutines.flow.MutableStateFlow | ||
import kotlinx.coroutines.flow.SharedFlow | ||
import kotlinx.coroutines.flow.StateFlow | ||
import kotlinx.coroutines.flow.asSharedFlow | ||
import kotlinx.coroutines.flow.asStateFlow | ||
import kotlinx.coroutines.launch | ||
|
||
abstract class BaseViewModel<State : UiState, SideEffect : UiSideEffect, Event : UiEvent> : | ||
ViewModel() { | ||
|
||
private val initialState: State by lazy { createInitialState() } | ||
abstract fun createInitialState(): State | ||
|
||
private val _uiState = MutableStateFlow(initialState) | ||
val uiState: StateFlow<State> = _uiState.asStateFlow() | ||
|
||
private val _sideEffect = MutableSharedFlow<SideEffect>() | ||
val sideEffect: SharedFlow<SideEffect> = _sideEffect.asSharedFlow() | ||
|
||
fun setState(reduce: State.() -> State) { | ||
_uiState.value = _uiState.value.reduce() | ||
} | ||
|
||
fun setSideEffect(builder: () -> SideEffect) { | ||
viewModelScope.launch { _sideEffect.emit(builder()) } | ||
} | ||
|
||
fun setEvent(event: Event) { | ||
viewModelScope.launch { handleEvent(event) } | ||
} | ||
|
||
protected abstract suspend fun handleEvent(event: Event) | ||
} |