Morniak
Morniak

Reputation: 998

OnNext not called when disposing the result of Observable.subscribe

I'm subscribing to an observable, but if I'm adding the disposable to the DisposeBag in my class, the onNext block is never called.

Here is my code :

@objc class AppleMusicPlaylistManager: NSObject {

    let disposeBag = DisposeBag()
    let playlists: [MPMediaPlaylist] = []

    func importAppleMusicPlaylist() {
        playlists.forEach { applePlaylist in
            applePlaylist.getItunesStoreTracks().subscribe(onNext: { tracks in
               // Doing things here
            }).addDisposableTo(disposeBag)
        }
    }
}

where getItunesStoreTracks return a RxSwift.Observable<[SoundsMusicITunesStore]> and the whole thing is used like that AppleMusicPlaylistManager().importAppleMusicPlaylist()

Upvotes: 1

Views: 1158

Answers (1)

Nikita Ermolenko
Nikita Ermolenko

Reputation: 2259

It all works as expected.

Current logic with disposeBag points out, that the observables will not be disposed of until the disposeBag is alive.

In your case - AppleMusicPlaylistManager().importAppleMusicPlaylist(), you create a manager and then you call the async requests, while the manager is deallocating. Thus all observables are deallocating as well.

In order for this to work correctly, you either have to set this manager as shared and use this method: AppleMusicPlaylistManager.shared.importAppleMusicPlaylist() or save this manager to some property in order to not deallocate immediately.

Upvotes: 1

Related Questions