Search code examples
c#unity-game-enginereactive-programmingunirx

What is the difference between a BehaviorSubject and a ReactiveProperty in UniRx?


What is the difference? To me they seem very similar... Why would you use one over the other?


Solution

  • They're similar in that they will both store the last given value & you can access them via the public property.

    Difference is:

    • ReactiveProperty will issue an event if and only if the value has changed.
    • BehaviorSubject will issue an event whatever the new value may be.

    In their C# code (which is open-sourced) ReacitveProperty checks equality of new value and last value; BehaviorSubject doesn't. In fact none of ISubject implementations checks the equality.

    When should you use one over another?

    I would use ReactiveProperty when I want callbacks only times the value has changed even though the substitution may occur more frequently. I would use BehaviourSubject when I want callbacks whenever the substitution occurred.

    In most cases ReactiveProperty is more useful because generally you want to react to changes. BehaviorSubject has its own use although less common.

    Other considerations:

    • ReactiveProperty.SetValueAndForceNotify() can be used to invoke callbacks regardless the equality.
    • IObservable.DistinctUntilChanged() can be used to (secondarily) introduce the equality check.