Last active
February 15, 2024 23:17
-
-
Save AlexGladkov/0e5bc2a888e63038a82e88b430e50b8d to your computer and use it in GitHub Desktop.
BaseViewModel (Migrating LiveData to Flow)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ExperimentalCoroutinesApi | |
abstract class BaseFlowViewModel<S, A, E>: ViewModel() { | |
private val TAG = BaseFlowViewModel::class.java.simpleName | |
private val _viewStates: MutableStateFlow<S?> = MutableStateFlow(null) | |
fun viewStates(): StateFlow<S?> = _viewStates | |
protected var viewState: S | |
get() = _viewStates.value | |
?: throw UninitializedPropertyAccessException("\"viewState\" was queried before being initialized") | |
set(value) { | |
/** StateFlow doesn't work with same values */ | |
if (_viewStates.value == value) { | |
_viewStates.value = null | |
} | |
_viewStates.value = value | |
} | |
private val _viewActions: MutableStateFlow<A?> = MutableStateFlow(null) | |
fun viewActions(): StateFlow<A?> = _viewActions | |
protected var viewAction: A | |
get() = _viewActions.value ?: throw UninitializedPropertyAccessException("\"viewAction\" was queried before being initialized") | |
set(value) { | |
/** StateFlow doesn't work with same values */ | |
if (_viewActions.value == value) { | |
_viewActions.value = null | |
} | |
_viewActions.value = value | |
} | |
abstract fun obtainEvent(viewEvent: E) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment