callbackFlow: taming the socket
Bridging a callback API into a Flow
Module 11's LiveViewModel opened an OkHttp WebSocket and handled incoming frames with a WebSocketListener β a classic callback API: you override onMessage, onFailure, and the OS calls them whenever something happens. That's a fine shape for a one-off side effect, but if you want the rest of your code to treat those frames as just another Flow β filterable, mappable, collectible with collectAsState() β you need a bridge. callbackFlow is that bridge: a flow builder purpose-built for wrapping callback-based APIs.
Inside a callbackFlow { ... } block you get a ProducerScope β call trySend(value) from any callback to push a value downstream, non-suspending, safe to call from someone else's callback thread. Buffering is automatic: trySend doesn't block, so a burst of fixes arriving faster than the collector processes them queues up (using the channel's default buffer) instead of getting silently dropped or blocking the network thread.