For example I have api to get list of Items:
Task<ICollection<Item>> GetItemsAsync();
I want to work with Items with ObservableCache<Item, int>
.
So, I created IItemsService
:
IObservableCache<Item, int> Items { get; }
with an implementation:
private IObservableCache<Items, int> _items;
public IObservableCache<Items, int> Items => _items ?? (_items = Create().AsObservableCache().Publish().RefCount());
private IObservable<IChangeSet<Items, int>> Create()
{
return ObservableChangeSet.Create<Items, int>(cache =>
{
var timer = Observable.Interval(TimeSpan.FromSeconds(1))
.SelectMany(_ => _api.GetItemsAsync())
.Retry()
.Subscribe(matchInfos => cache.EditDiff(matchInfos, EqualityComparer<MatchInfo>.Default));
return timer;
}, item => item.Id);
Then I use this service in view model to show items:
_service.Connect()
.Transform(item => new ItemViewModel(item))
.Bind(out items)
.Subscribe(_ => Initialized = true);
Initialized
property need to show/hide loading indicator.
I have a few questions:
- Is this a good way?
- I need to show "There is no Items" when Items Count is
0
andInitialized
property istrue
. But if server return 0 items -ObservableCache
will not raise notify, soInitialized
property will befalse
. What can I do with that? - When I dispose all subscriptions, the timer doesn't stop. I use
RefCount()
but it doesn't help.