observable()
Creates an observable object that tracks changes and notifies listeners. Observables can contain any type of value including primitives, objects, arrays, Maps, Sets, and more.Signatures
Parameters
The initial value for the observable. Can be:
- A direct value of any type
- A function that returns a value (lazy evaluation)
- A Promise that resolves to a value
- Another observable (creates a linked observable)
undefined.Returns
An observable proxy object with the following methods:
get()- Get the current value and track for changespeek()- Get the current value without trackingset(value)- Set a new valueonChange(callback)- Listen for changesdelete()- Delete the observable value
Examples
Basic usage
Observable objects
Observable arrays
Lazy initialization
Promise values
Empty observable
observablePrimitive()
Creates an observable for primitive values that cannot have child properties. This is more memory-efficient for primitive values since it doesn’t create a proxy.Signatures
Parameters
The initial primitive value. Can be:
- A primitive value (string, number, boolean, null, undefined)
- A Promise that resolves to a primitive value
undefined.Returns
An observable primitive with the following methods:
get()- Get the current value and track for changespeek()- Get the current value without trackingset(value)- Set a new valueonChange(callback)- Listen for changesdelete()- Delete the observable value
Observable<T>, does not support accessing child properties.Examples
Basic primitive
Boolean with toggle
Use with Promise
When to use observablePrimitive()
-
Use
observablePrimitive()when:- You only need to store primitive values (string, number, boolean, etc.)
- You want slightly better performance and memory usage
- You don’t need to access child properties
-
Use
observable()when:- You need to store objects or arrays
- You might need child property access
- You’re not sure about the type (observable handles both cases)
For most use cases,
observable() is the recommended choice as it handles all types seamlessly.