Last active
February 20, 2019 07:08
-
-
Save kboy-silvergym/3b9e20e95db44937ea0d8fc3dbcfc078 to your computer and use it in GitHub Desktop.
Hydra( https://github.com/malcommac/Hydra )のサンプル
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
import Hydra | |
// このようなダイアログが出るメソッドがあるとします。 | |
func showOKDialog(completion: (() -> Void)? = nil){ | |
let alert: UIAlertController = UIAlertController(title: "hoge", message: nil, preferredStyle: .alert) | |
let defaultAction = UIAlertAction(title: ok, style: .default, handler: { _ in | |
completion?() | |
}) | |
alert.addAction(defaultAction) | |
present(alert, animated: true, completion: nil) | |
} | |
// 上のメソッドをHydraを作ってPromise化したやつがこれ | |
func showDialogPromise() -> Promise<Bool> { | |
return Promise<Bool> (in: .main, { resolve, reject, _ in | |
showOKDialog(completion: { | |
resolve(true) | |
}) | |
}) | |
} | |
// -- ここから例文 -- | |
// ダイアログを連続で3回出したい場合 ふつう | |
// ネストが深い | |
showDialog() { | |
showDialog() { | |
showDialog() { | |
// something | |
} | |
} | |
} | |
// ダイアログを連続で3回出したい場合 Promise使うと | |
// ネストは深くならない | |
showDialogPromise() | |
.then({ _ -> Promise<Bool> in | |
return self.showDialogPromise() | |
}).then({ _ -> Promise<Bool> in | |
return self.showDialogPromise() | |
}).then({ isOk in | |
// somthing | |
}) | |
// さらにasync await使うと | |
// 非同期処理を同期っぽく扱える | |
async({ _ -> (Bool, Bool, Bool) in | |
let isOK1 = try await(self.showDialogPromise()) | |
let isOK2 = try await(self.showDialogPromise()) | |
let isOK3 = try await(self.showDialogPromise()) | |
return (isOK1, isOK2, isOK3) | |
}).then({ (isOK1, isOK2, isOK3) in | |
// something | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment