Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active May 3, 2023 03:01
Show Gist options
  • Save sgr-ksmt/c05cc1cf41a32b8b77e277394c29509a to your computer and use it in GitHub Desktop.
Save sgr-ksmt/c05cc1cf41a32b8b77e277394c29509a to your computer and use it in GitHub Desktop.
compose operator for RxSwift
struct ComposeTransformer<T, R> {
let transformer: (Observable<T>) -> Observable<R>
init(transformer: @escaping (Observable<T>) -> Observable<R>) {
self.transformer = transformer
}
func call(_ observable: Observable<T>) -> Observable<R> {
return transformer(observable)
}
}
extension ObservableType {
func compose<T>(_ transformer: ComposeTransformer<E, T>) -> Observable<T> {
return transformer.call(self.asObservable())
}
}
// ==================
// before
Observable.just([1, 2, 3, 4, 5])
.map{ $0.reduce(0, +) }
.subscribeOn(SerialDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
.subscribe({ event in
print(event)
})
// ==================
// after (1)
Observable.just([1, 2, 3, 4, 5])
.map{ $0.reduce(0, +) }
.compose(ComposeTransformer<Int, Int> { observable in
return observable
.subscribeOn(SerialDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
}).subscribe({ event in
print(event)
})
// ===================
// after (2)
let composeTransformer = ComposeTransformer<Int, Int> { observable in
return observable
.subscribeOn(SerialDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
}
Observable.just([1, 2, 3, 4, 5])
.map{ $0.reduce(0, +) }
.compose(composeTransformer)
.subscribe({ event in
print(event)
})
@llleodeleon
Copy link

Can we make it work with Any type? So I can reuse the same transformer to apply schedulers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment