Broadcastable
Updated on August 22, 2024Source codeTests
Broadcastable
is a class that enriches application state, allowing it to:
- Broadcast itself
- Store the
BroadcastChannel
instance used for broadcasting
Construct a Broadcastable
instance
The Broadcastable
constructor accepts two parameters:
state
Passes the state that will be made broadcastable.
state
can be any type supported by the structured clone algorithm.
options
Broadcastable
instance. See the Broadcastable constructor options section for more guidance.Broadcastable
constructor options
name
baleada
BroadcastChannel
instance that Broadcastable
uses to send messages.State and methods
state
The state passed to the Broadcastable
constructor.
If you assign a value directly to state
, a setter will pass the new value to setState
.
status
The status of the Broadcastable
instance.
One of 'ready'
, 'broadcasting'
, 'broadcasted'
, 'errored'
, or 'stopped'
.
channel
The BroadcastChannel
instance that Broadcastable
uses to send messages.
error
The error that was thrown during the last broadcast operation, when applicable.
setState(newState)
Broadcastable
instance's state
state
Broadcastable
instance (this
)broadcast()
Broadcastable
instance's state
Broadcastable
instance (this
)stop()
BroadcastChannel
instance that Broadcastable
uses to send messagesBroadcastable
instance (this
) Using with Listenable
Broadcastable
is designed to work seamlessly with Listenable
.
To listen for messages:
- Construct your
Listenable
instance, passingmessage
as the event type. - Use the
toMessageListenParams
function exported from Baleada Logic to easily format yourBroadcastable
instance and youronMessage
callback into parameters forListenable
'slisten
method.
import {
Listenable,
Broadcastable,
toMessageListenParams,
} from '@baleada/logic'
const broadcastable = new Broadcastable('hello world'),
message = new Listenable('message')
message.listen(...toMessageListenParams(
broadcastable,
event => {
console.log(event)
}
))
Using with TypeScript
The Broadcastable
constructor accepts one generic type that you can use to enforce a type for state
. By default, TypeScript will infer the type from the initial state you pass to the constructor, but you can specify the type manually if needed.
const withInferredTypes = new Broadcastable(0)
withInferredTypes.state = 'a' // Type error
const withManualTypes = new Broadcastable<string | number>(0)
withManualTypes.state = 'a' // No type error
API design compliance
options
object.state
setState
set<Property>
methodsstatus
, channel
, error
broadcast
, stop
stop
methodable