Home

BehaviorSubject

BehaviorSubject is a specialized subject in reactive programming that combines the capabilities of an observer and an observable with an added memory of the latest value. It stores the most recent value emitted and immediately provides that value to any new subscriber. When creating a BehaviorSubject, you must supply an initial value; this value becomes the current value until a new one is emitted.

On subscription, a BehaviorSubject immediately emits its current value to the subscriber, then continues to emit

Common use cases include representing state that changes over time and should be observable by multiple parts

Compared with ReplaySubject, BehaviorSubject stores only the latest value rather than buffering multiple values. This makes

any
subsequent
values
as
they
are
produced
by
next().
The
current
value
can
be
retrieved
synchronously
via
a
getValue()
method.
BehaviorSubject
participates
in
the
standard
observable
lifecycle:
if
the
subject
completes
or
errors,
new
subscribers
will
receive
the
terminal
notification
instead
of
a
value.
of
an
application,
such
as
UI
state,
form
input,
authentication
status,
or
feature
flags.
It
is
useful
when
components
need
to
start
with
a
meaningful
initial
value
and
always
have
access
to
the
latest
state
upon
subscription.
it
a
good
fit
for
state-like
streams
where
subscribers
should
observe
the
most
recent
state
immediately
upon
subscribing,
while
still
supporting
multicasting
and
reactive
updates.
BehaviorSubject
is
a
part
of
RxJS
and
related
reactive
libraries
implement
similar
constructs.