Observable
Observable
is a class that represents a stream of values. It is similar to Promise
in that it is a container for a value that will be available in the future. However, unlike Promise
, Observable
can emit multiple values over time.
const isLoggedIn = new Observable(false);
isLoggedIn.subscribe((nextValue: boolean) => {
if (nextValue) {
console.log('User is logged in');
} else {
console.log('User is logged out');
}
});
Reference
new Observable(initialValue?)
Creates a new Observable
instance with an optional initial value.
Arguments
initialValue?
- The initial value of theObservable
. Defaults toundefined
.
Caveats
- It's possible to instantiate an
Observable
without an initial value, but it's not recommended, as its value will beundefined
until it's set for the first time which can lead to unexpected behavior.
subscribe(onNext)
The subscribe
method is used to listen for changes to the Observable
's value. It returns a function that can be used to unsubscribe from the Observable
.
Arguments
onNext
- A function that will be called whenever theObservable
's value changes. It receives the new value as an argument.
Returns
unsubscribe
- A function that can be used to unsubscribe from theObservable
.
unsubscribe(onNext)
The unsubscribe
method is used to unsubscribe from the Observable
a specific onNext
callback.
Arguments
onNext
- TheonNext
callback to unsubscribe.
set value
The value
property is used to set the Observable
's value. Changing the value will trigger all subscribers and will trigger a rerender if the Observable
is used in a Component or a Hook.
get value
The value
property is used to get the Observable
's current value.
async first<T>(): Promise<T>
The first
method is used to get the Observable
's first value. If the Observable
has no value, it will wait for the first value to be set and return it.
Returns
Promise
- APromise
that resolves to theObservable
's current value if it has one, or waits for the first value to be set and resolves to it.
Usage
Conditional rendering of a component
See Conditional rendering of a component for a detailed explanation of this example.