Created
March 23, 2017 06:13
-
-
Save RyogaK/41f55c88250d5882f0e7d10240c4c866 to your computer and use it in GitHub Desktop.
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
// | |
// UIAlertController+Rx.swift | |
// | |
import Foundation | |
import RxSwift | |
protocol RxAlertActionType { | |
associatedtype Result | |
var title: String? { get } | |
var style: UIAlertActionStyle { get } | |
var result: Result { get } | |
} | |
struct RxAlertAction<R>: RxAlertActionType { | |
typealias Result = R | |
let title: String? | |
let style: UIAlertActionStyle | |
let result: R | |
} | |
struct RxDefaultAlertAction: RxAlertActionType { | |
typealias Result = RxAlertControllerResult | |
let title: String? | |
let style: UIAlertActionStyle | |
let result: Result | |
} | |
enum RxAlertControllerResult { | |
case Ok | |
} | |
extension UIAlertController { | |
static func rx_presentAlert<Action: RxAlertActionType, Result where Action.Result == Result>(viewController: UIViewController, title: String, message: String, preferredStyle: UIAlertControllerStyle = .Alert, animated: Bool = true, actions: [Action]) -> Observable<Result> { | |
return Observable.create { observer -> Disposable in | |
let alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) | |
actions.map { rxAction in | |
UIAlertAction(title: rxAction.title, style: rxAction.style, handler: { _ in | |
observer.onNext(rxAction.result) | |
observer.onCompleted() | |
}) | |
} | |
.forEach(alertController.addAction) | |
viewController.presentViewController(alertController, animated: animated, completion: nil) | |
return AnonymousDisposable { _ in | |
alertController.dismissViewControllerAnimated(true, completion: nil) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment