1 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
答案是您需要?jiǎng)?chuàng)建一個(gè)自定義運(yùn)算符。我在TransformWithInlineUpdate此處發(fā)布了一個(gè)要點(diǎn),您可以將其復(fù)制到您的解決方案中。示例用法是:
var users = new SourceCache<User, int>(user => user.Id);
var transformed = users.Connect()
.TransformWithInlineUpdate(u => new UserViewModel(u), (previousViewModel, updatedUser) =>
{
previousViewModel.User = updatedUser;
});
為了答案的完整性,這里是代碼:
public static IObservable<IChangeSet<TDestination, TKey>> TransformWithInlineUpdate<TObject, TKey, TDestination>(this IObservable<IChangeSet<TObject, TKey>> source,
Func<TObject, TDestination> transformFactory,
Action<TDestination, TObject> updateAction = null)
{
return source.Scan((ChangeAwareCache<TDestination, TKey>)null, (cache, changes) =>
{
//The change aware cache captures a history of all changes so downstream operators can replay the changes
if (cache == null)
cache = new ChangeAwareCache<TDestination, TKey>(changes.Count);
foreach (var change in changes)
{
switch (change.Reason)
{
case ChangeReason.Add:
cache.AddOrUpdate(transformFactory(change.Current), change.Key);
break;
case ChangeReason.Update:
{
if (updateAction == null) continue;
var previous = cache.Lookup(change.Key)
.ValueOrThrow(()=> new MissingKeyException($"{change.Key} is not found."));
//callback when an update has been received
updateAction(previous, change.Current);
//send a refresh as this will force downstream operators to filter, sort, group etc
cache.Refresh(change.Key);
}
break;
case ChangeReason.Remove:
cache.Remove(change.Key);
break;
case ChangeReason.Refresh:
cache.Refresh(change.Key);
break;
case ChangeReason.Moved:
//Do nothing !
break;
}
}
return cache;
}).Select(cache => cache.CaptureChanges()); //invoke capture changes to return the changeset
}
- 1 回答
- 0 關(guān)注
- 159 瀏覽
添加回答
舉報(bào)