BaseReactiveState
Base class/delegate for ViewModels and other objects that can trigger one-time events/actions and handle errors.
Make sure you always launch coroutines via launch (instead of the scope) to get automatic error handling.
Example:
// You can compose multiple events interfaces with simple inheritance (more elegant than sealed classes)
interface FooEvents : ErrorEvents, OtherEvents, AndMoreEvents {
fun onUserIsUnauthorized()
}
class FooViewModel(scope: CoroutineScope) : BaseReactiveState<FooEvents>(scope) {
private val _messages = MutableStateFlow<List<Message>>(emptyList())
val messages: StateFlow<List<Messages>> = _messages
init {
loadMessages()
}
fun loadMessages() {
launch {
// Let's pretend this function returns null for unauthorized requests
val messages = retrieveMessagesFromBackend()
if (messages == null) {
eventNotifier { onUserIsUnauthorized() }
} else {
_messages.value = messages
}
}
}
}
Functions
Watches observables for changes. Often useful to keep things in sync (e.g. CoroutineLauncher -> UI).
Watches observables for changes. Often useful to keep things in sync (e.g. CoroutineLauncher -> UI).
Creates a StateFlow that computes its value based on other StateFlows via an autoRun block.
Creates a StateFlow that computes its value based on other StateFlows via a suspendable coAutoRun block.
Helper for adding a completion handler to a CoroutineLauncher.
Launches a coroutine. Mark long-running coroutines by setting withLoading to loading state.
Launches a coroutine without any error handling or loading state tracking.
Runs OnInit.trigger for this class.