rxjs5: Delay unsubscription of a shared observable
<p>I have an observable that's expensive to create, so I've <code>shared</code> it. In certain cases, though, all of the subscribers unsubscribe and then immediately (or after a short delay) a new subscriber subscribes.</p>

<p>The actual observable is too complex to replicate here, but for the sake of argument:</p>

<pre><code>const heavyObservable = Rx.Observable.create((observer) =&gt; {
    console.log('I am expensive, avoid hitting this code');

    return Rx.Observable
            .interval(500) // these updates are cheap though!
            .subscribe(observer)
                .add(() =&gt; {
                    console.log('Cache has been destroyed, will have to be rebuild on next call');
                });
});
</code></pre>

<p>I don't want to hit the expensive code involved in creating this observable. I'd like to delay disconnection until after <em>n</em> ms. Is there a way to do this?</p>

<pre><code>const sharedObservable = heavyObservable
    .publish()
    // ideally I'm looking for a way to get refCount to wait for new 
    // subscribers for n ms before unsubscribing when refcount === 0
    .refCount(); 

// calling subscribe here invokes heavyObservable which can take a bit of time
const subscription1 = sharedObservable.subscribe();
// log: I am expensive, avoid hitting this code

// second call is "free" - the underlying observable is reused
const subscription2 = sharedObservable.subscribe();

subscription1.unsubscribe();
subscription2.unsubscribe();

// calling subscribe again here invokes heavyObservable over again
const subscription3 = sharedObservable.subscribe();
// log: I am expensive, avoid hitting this code
</code></pre>