Yes, you said it right that shared variables can be used which, in turn, can detect the changes and update the view accordingly !
Then why do we need Subject or BehaviorSubject ?
The simple answer is,
when it is only about changing the view directly as per updated shared variable something like below,
<div>Result : {{sharedService.result}}</div>
using shared variable makes sense. So, in shared service, you just change result to 10 and immediately view will be updated with 10 value.
But
what when result is 10, in (any) component, you want to run some piece of code/logic ???
How can you make sure that when result gets 10 value, some logic will be run (in the component ?)
something like below,
some.component.ts
if(sharedService.result === 10){
// This code can not run with shared variable approach
}
Q: Can we write something like above in component ?
A: yes
Q: After writing it, will it run the logic written inside?
A: No
Q: Why ?
A: Because, shared variables are (using service) referenced type. It means whenever you change the value, all references will be changed (for singleton service) in your application but code written in some.component.ts won't run or trigger.
Q: Why ?
A: Because in javascript/angular, to execute such type of scenario/code, you should have a mechanism of callback.
Q: What is callback ?
A: A function which can be passed as a parameter to any function which has ability to execute itself once the main function is executed.
That's the basic knowledge required to understand BehaviourSubject.
Now when you define a behaviourSubject in the service as below,
Shared.Service.ts
myBehaviorSubject = new BehaviourSubject(); // has ability to register a callback function
You can use myBehaviorSubject in any component as below,
some.component.ts
constructor(private sharedService:SharedService){
// below subscribe line registers a callback function with myBehaviorSubject.
this.sharedService.myBehavioirSubject.Subscribe((value)=>{ // This is callback function `(value)=>{...}`
if(value === 10){ // When value gets 10 value, below code will run automatically
// This code will run when condition is met
}
})
}
Now, behaviourSubject has some extra mechanism to emit the value. So if I emit 10 value from anywhere like this.myBehaviourSubject.next(10), due to internal mechanism of behaviourSubject, registered callback function will be called. As it is a function, when 10 value is emitted, a callback function will execture itself and it will run other logic written inside the function.
I hope, with this understanding you will be able to understand why shared variables are different from behaviourSubject