I’m interested in the lifecycle of an observable defines within a regular swift function - as a local variable.
Does the local variable observable get dealocated when the function returns? What are the conditions where I can count on my observable operating until it completes or errors out?
func testObservable()
{
let obs = Observable<Int>.interval( 2, MainScheduler.instance)
.subscribe(onNext: {print($0)}) //omitting dispose bag
}
Would the observable keep firing as long as it has a subscriber and disposed when it is unsubscribed?
How about this case? let disposeBag = disposeBag()
func testObservable()
{
let obs = Observable<Int>.interval( 2, MainScheduler.instance)
.subscribe(onNext: {print($0)})
.disposedBy(disposeBag)
}
The chain will break when either the source ends (by emitting a completed
or error
) or the sink stops accepting data (by calling dispose on its disposable.)
Therefore in your first function, the chain will stay active for the life of the program, and in the second function, the chain will die when the bag goes out of scope.