Open1
BaseViewModelを作って、MutableStateFlowをいい感じに使う
// shared module
abstract class BaseViewModel : ViewModel() {
protected fun <T> mutableStateFlow(value: T): DelegateMutableStateFlow<T> =
DelegateMutableStateFlow(MutableStateFlow(value))
protected suspend fun <T> DelegateMutableStateFlow<T>.emit(value: T): Unit =
emit(value)
}
class DelegateMutableStateFlow<T>(private val delegate: MutableStateFlow<T>) :
StateFlow<T> by delegate {
internal suspend fun emit(value: T) = delegate.emit(value)
}
// app(feature) modules
@HiltViewModel
class MainViewModel @Inject constructor() : BaseViewModel() {
val viewState = mutableStateFlow(MainViewState())
init {
viewModelScope.launch {
...
viewState.emit(newState)
}
}
}