Observing System Changes #

Hiro enables you to observe changes to the state of any systems used by using the SystemObserver helper or by subscribing an appropriate IObserver to that system. This can be useful for updating things such as UI in a reactive way.

The following example demonstrates how changes in the NakamaSystem can be observed.

Using the SystemObserver #

Using the SystemObserver helper class allows you to bind an action to be triggered whenever the system values change.

1
2
3
4
5
var disposer = SystemObserver<NakamaSystem>.Create(leaderboardsSystem, system => {
  Instance.Logger.Info($"System updated.");

  // Update UI elements etc as necessary here...
});

Implementing the IObserver interface #

Alternatively you can implement the IObserver<T> interface. This approach gives you more control and also allows you to observe different system states, such as if the system encounters an error.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class NakamaSystemObserver : IObserver<NakamaSystem>
{
  public NakamaSystemObserver(NakamaSystem nakamaSystem)
  {
    nakamaSystem.Subscribe(this);
  }

  public void OnCompleted()
  {
    Debug.Log("OnCompleted called");
  }

  public void OnError(Exception error)
  {
    Debug.LogError($"OnError called: {error.Message}");
  }

  public void OnNext(NakamaSystem nakamaSystem)
  {
    Debug.Log($"NakamaSystem updated for user {nakamaSystem.Account.Username}");
  }
}

Instantiate and use the class, for example in the GameCoordinator:

1
var nakamaSystemObserver = new NakamaSystemObserver(_nakamaSystem);