Cubit

abstract class Cubit<S : Any>(initialState: S) : StateEmitter<S>

A lightweight state-management class that exposes direct method calls instead of events.

Use Cubit when you don't need an event audit trail or EventTransformer strategies. It is shorter, easier to read, and equally testable.

class CounterCubit : Cubit<Int>(initialState = 0) {
fun increment() = emit(state + 1)
fun decrement() = emit(state - 1)
fun reset() = emit(0)
}

Cubit vs Bloc

CubitBloc
API styleDirect method callsDispatched events
Audit trailNo explicit event logFull event history via Bloc.eventsFlow
TransformersNot applicableDebounce, Restartable, Droppable, …
Observer hooksonCreate, onChange, onError, onCloseAll of the above + onEvent, onTransition
Best forSimple, well-understood state logicComplex flows, analytics, rate-limiting

Rule of thumb: Start with a Cubit. Upgrade to a Bloc when you need an event log or an EventTransformer strategy.

All methods are main-thread safe — the internal CoroutineScope runs on Dispatchers.Main. Override scope to change the dispatcher (e.g. for tests).

Constructors

Link copied to clipboard
constructor(initialState: S)

Properties

Link copied to clipboard
open override val errorsFlow: SharedFlow<Throwable>

Hot SharedFlow of errors surfaced via addError().

Link copied to clipboard
open override val isClosed: Boolean

true after close has been called. Further emissions become no-ops.

Link copied to clipboard
open override val state: S

The current state snapshot. Updated synchronously on the main thread.

Link copied to clipboard
open override val stateFlow: StateFlow<S>

Hot StateFlow that replays the latest state to new collectors.

Functions

Link copied to clipboard
open override fun close()

Closes this Cubit, cancels the coroutine scope, and marks it as closed. After calling close, emit and addError become no-ops.

Link copied to clipboard
open fun onChange(change: Change<S>)

Called after every emit. Contains the Change with the previous and next states.

Link copied to clipboard
open fun onClose()

Called when close completes. Use this to cancel any background coroutines or flush pending resources.

Link copied to clipboard
open fun onError(error: Throwable)

Called whenever addError is invoked.