We've been using Subjects in this book since Chapter 2, Reactive Programming with RxPHP, but there're multiple different variants of the Subject
class for more specific use cases where all of them are relevant to multicasting.
The BehaviorSubject
class extends the default Subject
class and lets us set a default value that is passed to its observer right on subscription. Consider this very simple example of BehaviorSubject
:
// behaviorSubject_01.php use Rx\Subject\BehaviorSubject; $subject = new BehaviorSubject(42); $subject->subscribe(new DebugSubject());
When DebugSubject
subscribes to the BehaviorSubject
class, the default value 42
is emitted immediately. This is a similar functionality to using the startWith()
operator.
The output is then just a single line:
$ php behaviorSubject_01.php 15:11:54 [] onNext: 42 (integer)