Created
May 17, 2016 12:30
-
-
Save gamako/01a3646103f065473ade766f9ad21287 to your computer and use it in GitHub Desktop.
RxSwift extension for flatmap like Swift2.x
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
extension Observable { | |
/** | |
example: | |
Observable<String>.of("1", "a", "3", "4") | |
.flatMap { Int($0) } | |
.subscribeNext { print("\($0)") } | |
result: | |
1 | |
3 | |
4 | |
*/ | |
func flatMap<T>(selector: (E) throws -> T?) -> Observable<T> { | |
return flatMap { try selector($0).map { Observable<T>.just($0) } ?? Observable<T>.empty() } | |
} | |
} | |
extension Driver { | |
/** | |
example: | |
Driver<String>.of("1", "a", "3", "4") | |
.flatMap { Int($0) } | |
.driveNext { print("\($0)") } | |
result: | |
1 | |
3 | |
4 | |
*/ | |
func flatMap<T>(selector: (E) -> T?) -> Driver<T> { | |
return flatMap { selector($0).map { Driver<T>.just($0) } ?? Driver<T>.empty() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment