Skip to content

Commit

Permalink
feature/#12: BaseViewModel 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
kangyein9892 committed Dec 17, 2024
1 parent 6a98a06 commit 3186454
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<State: UiState, Event: UiEvent, SideEffect: UiSideEffect>() : ViewModel() {

private val initialState: State by lazy { createInitialState() }
abstract fun createInitialState(): State

private val _uiState: MutableStateFlow<State> = MutableStateFlow(initialState)
val uiState = _uiState.asStateFlow()
val currentState: State
get() = _uiState.value

private val _event: MutableSharedFlow<Event> = MutableSharedFlow()
val event = _event.asSharedFlow()

private val _sideEffect: MutableSharedFlow<SideEffect> = 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) }
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.sopt.and.presentation.util.base

interface UiEvent
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.sopt.and.presentation.util.base

interface UiSideEffect
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.sopt.and.presentation.util.base

interface UiState

0 comments on commit 3186454

Please sign in to comment.