Reactive Extension data service

I want to have a generic in-memory cache class for creating, updating and deleting data. The base model inherits from an interface with a type string identifier.

interface IModel
{
  string Id { get; }
}

      

Working with creations and updates is easy. For example, if I want to subscribe to a stream and populate a dictionary, I know that creation is necessary if the model id doesn't already exist, otherwise it's an update.

My question is:
How would you handle deletions without introducing another class to carry my models ? I would like to save IObservable<TModel>

, not something like IObservable<Event<TModel>>

or IObservable<Pair<string, TModel>>

, but I can't see how. Is it possible?

interface IDataService<TModel>
{
  IObservable<TModel> DataStream { get; }
}

      

+3


source to share


1 answer


As shown in @Enigmativity, you can use nested observable sequences to solve this problem. This is covered in the section Matching sequences in IntroToRx.

How it works?

You might think the nested sequences should be something like a 2d array, or more specifically a jagged array . The outer sequence is the container for the inner sequences. The arrival of an internal sequence represents the creation of a model.

interface IDataService<TModel>
{
    IObservable<IObservable<TModel>> DataStream { get; }
}

      

Once you have an internal sequence, all the values ​​it produces are updates (except for the first one). The internal sequence will only update one identifier. When the internal sequence ends, submit the deletion.



This pattern works well for a variety of use cases as stated in the opening paragraph in the link above.

As a marble chart, you would have something like the following. Each line is an internal sequence.

m1  1---2----3--|
m2     a----|
m3       x----y---z--

      

This will lead to the following logical flow:

  • Create m1 with state '1'
  • Create m2 with state 'a'
  • Update m1 with value '2'
  • Create m3 with value 'x'
  • Delete m2
  • Update m1 with value '3'
  • Update m3 with value 'y'
  • Remove m1
  • Update m3 with value 'z'
+2


source







All Articles