public static IObservable <TResult> Timeout <T, TResult>(
            this IObservable <T> source,
            Duration period,
            Func <TResult> timeoutValueFactory,
            IScheduler scheduler = null)
        {
            return(Observable.Create <TResult>(o =>
            {
                scheduler = scheduler ?? Scheduler.Default;

                IConnectableObservable <object> sourceObject = source.Select(x => (object)x).Publish();
                var sourceComplete = new Subject <Unit>();

                IDisposable completeSub = sourceObject
                                          .Subscribe(_ => { }, o.OnError, () => sourceComplete.OnNext(Unit.Default));

                IObservable <object> timer = Observable.Timer(period, scheduler).Select(_ => _timerObject);

                IDisposable sub = sourceObject
                                  .StartWith(_startObject)
                                  .SelectMany(x => ReferenceEquals(x, _timerObject) ? Observable.Return(x) : timer.TakeUntil(sourceObject))
                                  .TakeUntil(sourceComplete)
                                  .Select(_ => timeoutValueFactory())
                                  .Subscribe(o);

                return new CompositeDisposable(sub, completeSub, sourceObject.Connect());
            }));
        }