Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe values not seen in other observers

I have an observable that emits unique values e.g.

var source=Observable.Range(1,100).Publish();
source.Connect();

I want to observe its values from e.g. two observers but each observer to get notified only for values not seen in other observers.

So if first observer contains the value 10 the second observer should never get notified for the 10 value.

Update

I chose @Asti`s answer cause it was first and although buggy it pointed to the right direction and up-voted @Shlomo's answer. Too bad I cannot accept both answers as @Shlomo answer was more correct and I really appreciate all his help we get on this tag.

like image 374
Apostolis Bekiaris Avatar asked Oct 21 '25 15:10

Apostolis Bekiaris


1 Answers

Observables aren't supposed to behave differently for different observers; a better approach would be to give each observer its own filtered observable.

That being said, if your constraints require that you need this behavior in a single observable - we can use a Round-Robin method.

    public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source)
    {
        for (; ; )
            foreach (var item in source.ToArray())
                yield return item;
    }

    public static IObservable<T> RoundRobin<T>(this IObservable<T> source)
    {
        var subscribers = new List<IObserver<T>>();
        var shared = source
            .Zip(subscribers.Repeat(), (value, observer) => (value, observer))
            .Publish()
            .RefCount();

        return Observable.Create<T>(observer =>
        {
            subscribers.Add(observer);
            var subscription = 
                shared
                .Where(pair => pair.observer == observer)
                .Select(pair => pair.value)
                .Subscribe(observer);

            var dispose = Disposable.Create(() => subscribers.Remove(observer));
            return new CompositeDisposable(subscription, dispose);
        });
    }

Usage:

var source = Observable.Range(1, 100).Publish();
var dist = source.RoundRobin();
dist.Subscribe(i => Console.WriteLine($"One sees {i}"));
dist.Subscribe(i => Console.WriteLine($"Two sees {i}"));

source.Connect();

Result:

One sees 1
Two sees 2
One sees 3
Two sees 4
One sees 5
Two sees 6
One sees 7
Two sees 8
One sees 9
Two sees 10

If you already have a list of observers, the code becomes much simpler.

like image 97
Asti Avatar answered Oct 24 '25 03:10

Asti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!