Skip to content

Commit

Permalink
#13 [Feat] : 추가 State, Event, SideEffect 공통 관리를 위한 BaseViewModel 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
imtaejugkim committed Dec 18, 2024
1 parent 2b4fdc0 commit 1c51977
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions app/src/main/java/org/sopt/and/presentation/core/BaseViewModel.kt
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)
}

0 comments on commit 1c51977

Please sign in to comment.