Observe settings via provider

Requires: main module.

One can subscribe to settings updates for a type with configuration provider's Observe method.

With prior assignment of sources:

provider.Observe<MySettings>().Subscribe(newSettings => {});

With sources passed on per-call basis:

provider.Observe<MySettings>(new JsonFileSource("settings1.json"))
    .Subscribe(newSettings => {});

Temporary subscriptions should be disposed of as they might hold on to resources in sources:

var subscription = provider.Observe<MySettings>().Subscribe(OnNewSettings);

using (subscription)
{
    // ...
}

Observe method behavior

  • OnError and OnCompleted notifications are never produced. Only successful settings updates are propagated to the observers. This means that there will be no notifications if initial attempt to provide settings fails with an error and no further data updates are published by the source.

  • The subscription is not guaranteed to immediately produce a notification. The first notification may be delayed due to data not having been fetched from the source yet. However, once a valid settings instance has been observed, all new observers receive a notification with current actual settings upon subscription. This notification is published on a background thread, so don't count on it being delivered after Subscribe call completes.

Best practices

It's recommended to obtain initial settings instance with Get method before subscribing to updates with Observe. This practice ensures correct error propagation, warms up the cache and eliminates situations where the settings are not ready yet on access attempt.

private volatile MySettings settings;
 
public Task InitializeAsync(IConfigurationProvider provider)
{
    OnSettingsUpdated(settings = provider.Get<MySettings>());
         
    provider.Observe<MySettings>()
      .Subscribe(newSettings => OnSettingsUpdated(settings = newSettings));
 
    return Task.CompletedTask;
}
 
private void OnSettingsUpdated(MySettings settings) 
{
    // ... 
}

Last updated