Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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)
})

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