Adding an observable sequence after subscription

后端 未结 2 352
北恋
北恋 2020-12-16 03:38

We are using Rx to monitor activity within our silverlight application so that we can display a message to the user after a period of inactivity.

We are turning eve

相关标签:
2条回答
  • 2020-12-16 04:05

    There's an overload to Merge that takes in an IObservable<IObservable<TSource>>. Make the outer sequence a Subject<IObservable<TSource>> and call OnNext to it when you want to add another source to the bunch. The Merge operator will receive the source and subscribe to it:

    var xss = new Subject<IObservable<int>>();
    xss.Merge().Subscribe(x => Console.WriteLine(x));
    
    xss.OnNext(Observable.Interval(TimeSpan.FromSeconds(1.0)).Select(x => 23 + 8 * (int)x));
    xss.OnNext(Observable.Interval(TimeSpan.FromSeconds(0.8)).Select(x => 17 + 3 * (int)x));
    xss.OnNext(Observable.Interval(TimeSpan.FromSeconds(1.3)).Select(x => 31 + 2 * (int)x));
    ...
    
    0 讨论(0)
  • 2020-12-16 04:09

    The easiest way to do this would be to use an intermediate subject in place of the Merge calls.

    Subject<DateTime> allActivities = new Subject<DateTime>();
    var activitySubscriptions = new CompositeDisposable();
    
    activitySubscriptions.Add(mouseMoveActivity.Subscribe(allActivities));
    activitySubscriptions.Add(mouseLeftButtonActivity.Subscribe(allActivities));
    //etc ...
    
    //subscribe to activities
    allActivities.Throttle(timeSpan)
                 .Subscribe(timeoutAction);
    
    //later add another
    activitySubscriptions.Add(newActivity.Subscribe(allActivities));
    

    The Subject class will stop passing OnNext (and further OnError and OnCompleted) events from any of the observables it is subscribed to if it receives any OnError or OnCompleted.

    The main difference between this approach and your sample is that it subscribes to all the events when the subject is created, rather than when you subscribe to the merged observable. Since all of the observables in your example are hot, the difference should not be noticeable.

    0 讨论(0)
提交回复
热议问题