I have an IObservable of items with a timestamp. I use the Scan method to wrap each item and add a reference to the last valid wrapped item which was received.
IObservable<IWrappedItem> wrappedItems =
allItems.Scan(seedItem,
(lastWrappedItem, currentItem) =>
WrapItem(currentItem, lastWrappedItem)));
This is the signature of WrapItem:
IWrappedItem WrapItem(Item currentItem, IWrappedItem lastItem);
We needed to change the WrapItem method so it skips invalid (not-null) items and returns null.
The seedItem will most probably be null, and the WrapItem method can handle it.
I need to update the way I use Scan with something like this:
IObservable<IWrappedItem> wrappedItems = allItems.Scan(seedItem, (lastWrappedItem, currentItem) =>
{
IWrappedItem wrappedItem = WrapItem(currentItem, lastWrappedItem);
if (wrappedItem == null)
{
// Do something clever to skip this invalid item
// Next item should have a reference to lastWrappedItem
}
return wrappedItem;
}));
How can I implement this behavior without returning null values to the new collection, while keeping the Observable pattern? Is there a different method that I should use instead of "Scan"?
EDIT: @TheodorZoulias - Thanks for your important comment. I tested it and saw that two parallel observers will not run concurrently, but the second one receives the last
lastWrappedItemobject of the first one as its seed instead ofnull. So I wrapped my observable withDeferas @Enigmativity suggested and it works correctly.I found the answer to my question, I implemented a custom generic
Scanmethod that receives theWrapItemfunction and ignores null values returned from it. It implementsScanusingSelectandWheremethods.This is my updated implementation:
This method can be used like this:
I didn't benchmark the new method to assess the performance penalty, but I believe it would be slower than the original Scan method...