3

I have 2 observables A and B.

I would like to generate C that emits only when A emits, with a combination of the value just pushed in A, and the most recent value in B.

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • 2
    I'm still looking if there is a built in implantation for what your describing. your essentally describing this : http://rxmarbles.com/#withLatestFrom where the top line is A and the Bottom is B , correct ? – eran otzap Feb 08 '17 at 21:40
  • @eranotzap That's it! It's what I was looking for. I have never used that operator until now. Thank you! – SuperJMN Feb 08 '17 at 22:56
  • @SuperJMN I'd like love to know if you find or implement this in C# i was not able to find it. I can think of how to implement it myself.. – eran otzap Feb 09 '17 at 06:26
  • 1
    There's a method called `Observable.WithLatestFrom`. Where did you look? – Shlomo Feb 09 '17 at 19:11
  • @Shlomo I didn't even know that method existed! – SuperJMN Feb 09 '17 at 22:33

1 Answers1

1

Here you go, I think this will do

let's say that A is an observable of char and B an Observable of int.

A calls on next every 3 sec. B calls on next every 1 sec.

Take the next from A with the current latest of B.

    static void Main(string[] args)
    {            
        var chrObservable = CharEnumerable().ToObservable();
        var timer1 = Observable.Interval(TimeSpan.FromSeconds(3));

        var chrAtInterval = timer1.Zip(chrObservable, (ts,c) => c);

        var numberObservable = NumEnumerable().ToObservable();
        var timer2 = Observable.Interval(TimeSpan.FromSeconds(1));

        var numberAtInterval = timer2.Zip(numberObservable, (ts,n) => n);

        chrAtInterval.WithLatestFrom(numberAtInterval,(c, n) => new{c,n})
               .Subscribe(pair => Console.WriteLine(pair.c + ":" + pair.n));

        Console.WriteLine("Waiting...");
        Console.ReadKey();
    }

    private static IEnumerable<int> NumEnumerable()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return i;
        }
    }

    private static IEnumerable<char> CharEnumerable()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return (char)(i + 65);
        }
    }
eran otzap
  • 12,293
  • 20
  • 84
  • 139
  • Yes, that's it! I have implemented in a similar scenario. Your example illustrates the usage perfectly. Thank you! – SuperJMN Feb 09 '17 at 22:36