Skip to content

Instantly share code, notes, and snippets.

@ppth0608
Created July 14, 2019 04:22
Show Gist options
  • Save ppth0608/29fbb17c4a0c9f932b7c5928699692f5 to your computer and use it in GitHub Desktop.
Save ppth0608/29fbb17c4a0c9f932b7c5928699692f5 to your computer and use it in GitHub Desktop.
How to using UIAlertController with RxSwift
import RxSwift
import UIKit
extension UIAlertController {
struct AlertAction {
var title: String?
var style: UIAlertAction.Style
static func action(title: String?, style: UIAlertAction.Style = .default) -> AlertAction {
return AlertAction(title: title, style: style)
}
}
static func present(
in viewController: UIViewController?,
title: String?,
message: String? = nil,
style: UIAlertController.Style = .alert,
actions: [AlertAction])
-> Observable<Int> {
return Observable.create { observer in
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
actions.enumerated().forEach { index, action in
let action = UIAlertAction(title: action.title, style: action.style) { _ in
observer.onNext(index)
observer.onCompleted()
}
alertController.addAction(action)
}
viewController?.present(alertController, animated: true, completion: nil)
return Disposables.create { alertController.dismiss(animated: true, completion: nil) }
}
}
}
/////////
//Usage//
/////////
action.deleteClip
.flatMapLatest { clip -> Observable<(Clip, Int)> in
let actions = [UIAlertController.AlertAction(title: "아니요", style: .cancel), UIAlertController.AlertAction(title: "예", style: .default)]
return UIAlertController.present(in: Navigator.topMostViewController, title: "aaaa", actions: actions)
.map { (clip, $0) }
}
.filter { $0.1 == 1 }
.map { $0.0 }
.do(onNext: { [weak self] _ in self?.state.loadingStatus.value = .loading })
.flatMapLatest(provider.clipService.remove)
.do(onNext: { [weak self] _ in self?.state.loadingStatus.value = .ready })
.map { [weak self] clip -> [Clip] in
let clips = self?.state.sections.value.first?.items ?? []
return clips.removed(at: clip)
}
.map { [Section<Clip>(items: $0)] }
.bind(to: state.sections)
.disposed(by: disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment