Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6070831
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T09:58:41+00:00 2026-05-23T09:58:41+00:00

I’m using the Reactive Extensions (Rx) and a repository pattern to facilitate getting data

  • 0

I’m using the Reactive Extensions (Rx) and a repository pattern to facilitate getting data from a relatively slow data source. I have the following (simplified) interface:

public interface IStorage
{
    IObservable<INode> Fetch(IObservable<Guid> ids);
}

Creating an instance of the implementation of IStorage is slow – think creating a web service or db connection. Each Guid in the ids observable results in a one-to-one INode (or null) in the return observable and each result is expensive. Therefore , it makes sense to me only to instantiate IStorage only if I have at least one value to fetch and then to use IStorage to fetch only the values once for each Guid.

To limit the calls to IStorage I cache the results in my Repository class that looks like this:

public class Repository
{
    private Dictionary<Guid, INode> NodeCache { get; set; }

    private Func<IStorage> StorageFactory { get; set; }

    public IObservable<INode> Fetch(IObservable<Guid> ids)
    {
        var lazyStorage = new Lazy<IStorage>(this.StorageFactory);

        // from id in ids
        // if NodeCache contains id select NodeCache[id]
        // else select node from lazyStorage.Value.Fetch(...)
    }
}

In the Repository.Fetch(...) method I’ve included comments indicating what I’m trying to do.

Essentially though, if the NodeCache contains all of the ids being fetched then IStorage is never instantiated and the results are returned with almost no delay. However, if any one id is not in the cache then IStorage is instantiated and all of the unknown ids are passed through the IStorage.Fetch(...) method.

The one-to-one mapping, including order preservation, needs to be maintained.

Any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T09:58:42+00:00Added an answer on May 23, 2026 at 9:58 am

    It took a while to work it out, but I finally got my own solution.

    I have defined two extension methods called FromCacheOrFetch with these signatures:

    IObservable<R> FromCacheOrFetch<T, R>(
        this IObservable<T> source,
        Func<T, R> cache,
        Func<IObservable<T>, IObservable<R>> fetch,
        IScheduler scheduler)
            where R : class
    
    IObservable<R> FromCacheOrFetch<T, R>(
        this IObservable<T> source,
        Func<T, Maybe<R>> cache,
        Func<IObservable<T>, IObservable<R>> fetch,
        IScheduler scheduler)
    

    The first uses standard CLR/Rx types and the second uses a Maybe monad (nullable types not restricted to value types).

    The first just turns the Func<T, R> into Func<T, Maybe<R>> and calls the second method.

    The basic idea behind is that when the source is to be queried the cache is examined for each value to see if a result already exists and if it does the result is immediately returned. If, however, any result is missing then and only then is the fetch function called by passing in a Subject<T> and now all cache misses are passed through the fetch function. The calling code is responsible for adding the results to the cache. The code asynchronously processes all the values through the fetch function and reassembles the results, along with cached results, into the correct order.

    Works like a treat. 🙂

    Here’s the code:

    public static IObservable<R> FromCacheOrFetch<T, R>(this IObservable<T> source,
        Func<T, R> cache, Func<IObservable<T>, IObservable<R>> fetch,
        IScheduler scheduler)
            where R : class
    {
        return source
            .FromCacheOrFetch<T, R>(t => cache(t).ToMaybe(null), fetch, scheduler);
    }
    
    public static IObservable<R> FromCacheOrFetch<T, R>(this IObservable<T> source,
        Func<T, Maybe<R>> cache, Func<IObservable<T>, IObservable<R>> fetch,
        IScheduler scheduler)
    {
        var results = new Subject<R>();
    
        var disposables = new CompositeDisposable();
    
        var loop = new EventLoopScheduler();
        disposables.Add(loop);
    
        var sourceDone = false;
        var pairsDone = true;
        var exception = (Exception)null;
    
        var fetchIn = new Subject<T>();
        var fetchOut = (IObservable<R>)null;
        var pairs = (IObservable<KeyValuePair<int, R>>)null;
    
        var lookup = new Dictionary<T, int>();
        var list = new List<Maybe<R>>();
        var cursor = 0;
    
        Action checkCleanup = () =>
        {
            if (sourceDone && pairsDone)
            {
                if (exception == null)
                {
                    results.OnCompleted();
                }
                else
                {
                    results.OnError(exception);
                }
                loop.Schedule(() => disposables.Dispose());
            }
        };
    
        Action dequeue = () =>
        {
            while (cursor != list.Count)
            {
                var mr = list[cursor];
                if (mr.HasValue)
                {
                    results.OnNext(mr.Value);
                    cursor++;
                }
                else
                {
                    break;
                }
            }
        };
    
        Action<KeyValuePair<int, R>> nextPairs = kvp =>
        {
            list[kvp.Key] = Maybe<R>.Something(kvp.Value);
            dequeue();
        };
    
        Action<Exception> errorPairs = ex =>
        {
            fetchIn.OnCompleted();
            pairsDone = true;
            exception = ex;
            checkCleanup();
        };
    
        Action completedPairs = () =>
        {
            pairsDone = true;
            checkCleanup();
        };
    
        Action<T> sourceNext = t =>
        {
            var mr = cache(t);
            list.Add(mr);
            if (mr.IsNothing)
            {
                lookup[t] = list.Count - 1;
                if (fetchOut == null)
                {
                    pairsDone = false;
                    fetchOut = fetch(fetchIn.ObserveOn(Scheduler.ThreadPool));
                    pairs = fetchIn
                        .Select(x => lookup[x])
                        .Zip(fetchOut, (i, r2) => new KeyValuePair<int, R>(i, r2));
                    disposables.Add(pairs
                        .ObserveOn(loop)
                        .Subscribe(nextPairs, errorPairs, completedPairs));
                }
                fetchIn.OnNext(t);
            }
            else
            {
                dequeue();
            }
        };
    
        Action<Exception> errorSource = ex =>
        {
            sourceDone = true;
            exception = ex;
            fetchIn.OnCompleted();
            checkCleanup();
        };
    
        Action completedSource = () =>
        {
            sourceDone = true;
            fetchIn.OnCompleted();
            checkCleanup();
        };
    
        disposables.Add(source
            .ObserveOn(loop)
            .Subscribe(sourceNext, errorSource, completedSource));
    
        return results.ObserveOn(scheduler);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bunch of posts stored in text files formatted in yaml/textile (from
I have some data like this: 1 2 3 4 5 9 2 6
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
Does anyone know how can I replace this 2 symbol below from the string
I'm making a simple page using Google Maps API 3. My first. One marker
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.