Once
Once copied to clipboard
Execute closure just once!!! Once is a micro framework.
Once
Execute closure once!!! Once is a micro framework.
import Once
class ViewController: UIViewController {
private var dataSource = DataSource()
lazy var onceReloader: OnceClosure = execute_once {
print("execute once")
self.dataSource.reload()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onceReloader?()
}
}
Legacy...
class ViewController: UIViewController {
private var dataSource = DataSource()
private var callFirst = true
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if callFirst {
reloadOnce()
callFirst = falee
}
}
func reloadOnce() {
print("execute once")
self.dataSource.reload()
}
}
Features
- Execute closure just once.
- Don't need to have any flags that closure called or not.
- This function doesn't capture any objects by using
no-escapedclosure.- You don't have to use
[weak self], [unowned self].
- You don't have to use
- Micro library!
How to use
-
- Import framework
import Once
-
- Define
lazy varinstance.
Note: Don't forget to write parameter:OnceClosure
- Define
class ViewController: UIViewController {
// as closure
lazy var onceReloader: OnceClosure = execute_once {
print("execute once")
self.dataSource.reload()
}
// or function
lazy var onceReloader2: OnceClosure = self.reloadOnce()
func reloadOnce() -> OnceClosure {
return execute_once {
print("execute once")
self.dataSource.reload()
}
}
}
-
- Execute once closure!! (need
?)
- Execute once closure!! (need
class ViewController: UIViewController {
// ...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onceReloader?()
}
}
Caution
Once-closure will not work anymore if it is assigned nil before executing.
import Once
class ViewController: UIViewController {
private var dataSource = DataSource()
lazy var onceReloader: OnceClosure = execute_once {
print("execute once")
self.dataSource.reload()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onceReloader = nil
onceReloader?() // doesn't work.
}
}
Requirements
- iOS 8.0+
- Xcode 8+
- Swift 3
Installation
You can install with carthage or SPM.
Carthage
- Add the following to your Cartfile:
github 'sgr-ksmt/once'
- Then run command.
Communication
- If you found a bug, please open an issue. :bow:
- Also, if you have a feature request, please open an issue. :thumbsup:
- If you want to contribute, submit a pull request.:muscle:
License
Once is under MIT license. See the LICENSE file for more info.