|
| 1 | +package com.yapp.ui.base |
| 2 | + |
| 3 | +import androidx.compose.runtime.Composable |
| 4 | +import androidx.compose.runtime.LaunchedEffect |
| 5 | +import androidx.compose.runtime.State |
| 6 | +import androidx.compose.runtime.getValue |
| 7 | +import androidx.compose.runtime.rememberUpdatedState |
| 8 | +import androidx.lifecycle.Lifecycle |
| 9 | +import androidx.lifecycle.ViewModel |
| 10 | +import androidx.lifecycle.compose.LocalLifecycleOwner |
| 11 | +import androidx.lifecycle.compose.collectAsStateWithLifecycle |
| 12 | +import androidx.lifecycle.repeatOnLifecycle |
| 13 | +import androidx.lifecycle.viewModelScope |
| 14 | +import kotlinx.coroutines.Dispatchers |
| 15 | +import kotlinx.coroutines.channels.Channel |
| 16 | +import kotlinx.coroutines.channels.Channel.Factory.BUFFERED |
| 17 | +import kotlinx.coroutines.flow.MutableStateFlow |
| 18 | +import kotlinx.coroutines.flow.asStateFlow |
| 19 | +import kotlinx.coroutines.flow.receiveAsFlow |
| 20 | +import kotlinx.coroutines.launch |
| 21 | +import kotlinx.coroutines.flow.update |
| 22 | +import kotlinx.coroutines.withContext |
| 23 | + |
| 24 | +abstract class BaseViewModel<S : UiState, I : UiIntent, SE : UiSideEffect>( |
| 25 | + initialState: S, |
| 26 | +) : ViewModel() { |
| 27 | + private val _state = MutableStateFlow(initialState) |
| 28 | + protected val state = _state.asStateFlow() |
| 29 | + |
| 30 | + private val _sideEffect: Channel<SE> = Channel(BUFFERED) |
| 31 | + protected val sideEffect = _sideEffect.receiveAsFlow() |
| 32 | + |
| 33 | + fun onIntent(intent: I) = |
| 34 | + viewModelScope.launch { |
| 35 | + handleIntent(intent) |
| 36 | + } |
| 37 | + |
| 38 | + protected abstract suspend fun handleIntent(intent: I) |
| 39 | + |
| 40 | + protected fun reduce(block: S.() -> S) = |
| 41 | + viewModelScope.launch { |
| 42 | + _state.update { it.block() } |
| 43 | + } |
| 44 | + |
| 45 | + protected fun postSideEffect(effect: SE) = |
| 46 | + viewModelScope.launch { _sideEffect.send(effect) } |
| 47 | + |
| 48 | + @Composable |
| 49 | + fun collectAsState( |
| 50 | + lifecycleState: Lifecycle.State = Lifecycle.State.STARTED, |
| 51 | + ): State<S> { |
| 52 | + return state.collectAsStateWithLifecycle(minActiveState = lifecycleState) |
| 53 | + } |
| 54 | + |
| 55 | + @Composable |
| 56 | + fun collectSideEffect( |
| 57 | + sideEffect: (suspend (sideEffect: SE) -> Unit), |
| 58 | + ) { |
| 59 | + val sideEffectFlow = this.sideEffect |
| 60 | + val lifecycleOwner = LocalLifecycleOwner.current |
| 61 | + |
| 62 | + val callback by rememberUpdatedState(newValue = sideEffect) |
| 63 | + |
| 64 | + LaunchedEffect(sideEffectFlow, lifecycleOwner) { |
| 65 | + lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { |
| 66 | + withContext(Dispatchers.Main.immediate) { |
| 67 | + sideEffectFlow.collect { callback(it) } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments