Last active
May 3, 2023 03:01
-
-
Save sgr-ksmt/c05cc1cf41a32b8b77e277394c29509a to your computer and use it in GitHub Desktop.
compose operator for RxSwift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ================== | |
// 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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can we make it work with Any type? So I can reuse the same transformer to apply schedulers