Bloc
Business Logic Component — the core state-management class.
A Bloc receives typed events, routes each one to a registered handler via on, and emits new states through emit. Every state change is observable via stateFlow.
// 1. Define events
sealed class CounterEvent {
data object Increment : CounterEvent()
data object Decrement : CounterEvent()
}
// 2. Create the Bloc
class CounterBloc : Bloc<Int, CounterEvent>(initialState = 0) {
init {
on<CounterEvent.Increment> { _, emit -> emit(state + 1) }
on<CounterEvent.Decrement> { _, emit -> emit(state - 1) }
}
}
// 3. Send events
counterBloc.send(CounterEvent.Increment)Handler signature
typealias Handler<E, S> = suspend (event: E, emit: (S) -> Unit) -> UnitType Parameters
State type — must implement equals (data class or primitive recommended).
Event type — sealed class / interface recommended.
Inheritors
Properties
Functions
Signals an error without encoding it into the state type. Broadcasts to errorsFlow, then calls onError and BlocObserver.onError.
Called when close completes. Cancel any background coroutines here. Always call super.onClose() to forward to BlocObserver.onClose.
Called whenever addError is invoked. Always call super.onError(error) to forward to BlocObserver.onError.
Called immediately before an event is dispatched to its handler. Always call super.onEvent(event) to forward to BlocObserver.onEvent.
Called after a synchronous emit that has an active event context. Always call super.onTransition(transition) to forward to BlocObserver.onTransition.