Skip to content

Chaining collections using Populate extension methods

Andy Smolak edited this page Apr 27, 2021 · 1 revision

While it is easy to compose long chains of derived change sets from a single SourceCache or SourceList by directly connecting to each IObservable in series, any changes to those intermediate collections (ex. changing a Transform call) requires resubscription by each downstream observer.

The methods PopulateFrom and PopulateInto allow you to easily account for this by managing subscriptions to a source cache from other upstream observable sources.

Given a source list or cache that will be made available in some class to outside consumers:

private SourceCache<Person> _peopleCache;
public IObservableCache PeopleCache { get; }
//provide a reference to subscription for unsubscribing/switching sources
private IDisposable _subscription; 
...
PeopleCache = _peopleCache.Connect().AsObservableCache();

The source data for this cache can then be provided from another IObservable:

_subscription = PeopleFromSpainCache.Connect.PopulateInto(_peopleCache);

A ViewModel, for instance, can bind this cache to an observablecollection for display in the UI:

Model.PeopleCache.Connect().Transform(p => new PeopleViewModel(p)).ObserveOnDispatcher()
                .Bind(out _peopleItemSource).DisposeMany().Subscribe();

Then, the source of the cache data can be changed later without having to worry about re-binding or making changes in the viewmodel:

_subscription = PeopleFromPortugalCache.Connect.PopulateInto(_peopleCache);

PopulateFrom from works in a very similar manner, but allows you to connect a SourceCache to any Observable stream, not just an observable cache or list.