diff --git a/presentation/src/main/java/org/sopt/and/presentation/util/base/BaseViewModel.kt b/presentation/src/main/java/org/sopt/and/presentation/util/base/BaseViewModel.kt new file mode 100644 index 0000000..9081540 --- /dev/null +++ b/presentation/src/main/java/org/sopt/and/presentation/util/base/BaseViewModel.kt @@ -0,0 +1,45 @@ +package org.sopt.and.presentation.util.base + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +abstract class BaseViewModel() : ViewModel() { + + private val initialState: State by lazy { createInitialState() } + abstract fun createInitialState(): State + + private val _uiState: MutableStateFlow = MutableStateFlow(initialState) + val uiState = _uiState.asStateFlow() + val currentState: State + get() = _uiState.value + + private val _event: MutableSharedFlow = MutableSharedFlow() + val event = _event.asSharedFlow() + + private val _sideEffect: MutableSharedFlow = MutableSharedFlow() + val sideEffect = _sideEffect.asSharedFlow() + + fun setState(reduce: State.() -> State) { + _uiState.value = currentState.reduce() + } + + open fun setEvent(event: Event) { + dispatchEvent(event) + } + + private fun dispatchEvent(event: Event) = viewModelScope.launch { + handleEvent(event) + } + + protected abstract suspend fun handleEvent(event: Event) + + fun setSideEffect(sideEffect: SideEffect) { + viewModelScope.launch { _sideEffect.emit(sideEffect) } + } + +} \ No newline at end of file diff --git a/presentation/src/main/java/org/sopt/and/presentation/util/base/UiEvent.kt b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiEvent.kt new file mode 100644 index 0000000..6d73367 --- /dev/null +++ b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiEvent.kt @@ -0,0 +1,3 @@ +package org.sopt.and.presentation.util.base + +interface UiEvent \ No newline at end of file diff --git a/presentation/src/main/java/org/sopt/and/presentation/util/base/UiSideEffect.kt b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiSideEffect.kt new file mode 100644 index 0000000..a59d6a5 --- /dev/null +++ b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiSideEffect.kt @@ -0,0 +1,3 @@ +package org.sopt.and.presentation.util.base + +interface UiSideEffect diff --git a/presentation/src/main/java/org/sopt/and/presentation/util/base/UiState.kt b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiState.kt new file mode 100644 index 0000000..c467772 --- /dev/null +++ b/presentation/src/main/java/org/sopt/and/presentation/util/base/UiState.kt @@ -0,0 +1,3 @@ +package org.sopt.and.presentation.util.base + +interface UiState \ No newline at end of file