Search code examples
swiftrx-swiftreactivex

Is it possible to make `ReplaySubject` to run a closure on being subscribed to?


I want to create a cold observable that would only start doing expensive operation if there is an actual subscription. ReplaySubject would fit nicely except for the part that I need to be able to start an expensive background operation when the actual subscription is made and not on create of the observable. Is there a way to do so? Some sort of onSubscribed { ... } method.


Solution

  • Here are a couple of options:

    Adding the expensive operation to a doOn(onSubscribe:) that's in between the Observable and the subscription:

    let observable = Observable.of(1, 2)
        .doOn(onSubscribe: { _ in
            expensiveOperation()
        })
    
    observable
        .subscribeNext { e in
            print(e)
        }
    

    Making the Observable connectable and separating the doOn(onSubscribe:):

    let observable = Observable.of(1, 2)
        .publish()
    
    observable
        .doOn(onSubscribe: { _ in
            expensiveOperation()
        })
        .subscribe()
    
    observable
        .subscribeNext { e in
            print(e)
        }
    
    observable.connect()