Skip to content

Instantly share code, notes, and snippets.

@gamako
Created May 17, 2016 12:30
Show Gist options
  • Save gamako/01a3646103f065473ade766f9ad21287 to your computer and use it in GitHub Desktop.
Save gamako/01a3646103f065473ade766f9ad21287 to your computer and use it in GitHub Desktop.
RxSwift extension for flatmap like Swift2.x
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