Skip to main content

BlocObserver

A bloc exposes a StateStream and a SideEffectStream which are essentially Kotlin Flows. The question is how can a Kotlin Flow be observed in Swift? Different solutions have been proposed:

Some of these solutions are more generic than what we need for our purpose which is simply be able to observe the streams in SwiftUI and update the view when state changes.

The BlocObserver class:

  • observes both streams and exposes them as @Published properties (-> the BlocObserver needs to be an ObservableObject)
  • state and sideEffect are the @Published properties than can be observed by the view
  • creates a lifecycle used to unsubscribe from the bloc, the lifecycle is tied to the "lifecycle" of the BlocObserver object itself
    private let holder = BlocHolder { CalculatorKt.bloc(context: $0) }

@ObservedObject
private var model: BlocObserver<CalculatorState, CalculatorAction, KotlinUnit>

init() {
self.model = BlocObserver(self.holder.value)
}
tip

The lifecycle is tied to the lifecycle of the BlocObserver object itself. As with BlocHolder that means that you need to keep an explicit reference to that object like in the example above. See also: BlocHolder