Dealing With Resources in RxSwift

final class AudioSession: Disposable {
let audioPlayer: AVAudioPlayer
init(url: URL) throws {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.play()
}
func dispose() {
audioPlayer.stop()
}
}
let session = Observable.using({
try AudioSession(url: url)
},
observableFactory: { audioSession in
Observable<Never>.never()
})
return Observable<Int>.interval(
.milliseconds(100),
scheduler: MainScheduler.instance
)
.flatMap { _ in
Observable.just(audioSession.audioPlayer.currentTime)
}
togglePlay // an Observable<Void>
.subscribe(onNext: audioSession.audioPlayer.toggle)
.disposed(by: audioSession.disposeBag)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel Tartaglia

Daniel Tartaglia

I started programming as a hobby in the late ’70s and professionally in the late ’90s. I’ve been writing iOS apps since 2010 and using RxSwift since 2015.