Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yakushevichsv/8460d239553857592cc72bb0b0362f08 to your computer and use it in GitHub Desktop.
Save yakushevichsv/8460d239553857592cc72bb0b0362f08 to your computer and use it in GitHub Desktop.
Extension of MainThreadRunnerType For Weakly Calling Block
extension MainThreadRunnerType {
static func weakify<Object: AnyObject, Input>(_ obj: Object,
method: @escaping ((Object) -> (Input) -> Void)) -> ((Input) -> Void) {
return { [weak obj] value in
guard let obj = obj else { return }
method(obj)(value)
}
}
static func weakify<Object: AnyObject>(_ obj: Object,
method: @escaping ((Object) -> () -> Void)) -> (() -> Void) {
return { [weak obj] in
guard let obj = obj else { return }
method(obj)()
}
}
func runOnMainWeakly<Object: AnyObject, T>(_ obj: Object,
parameter: T,
method: @escaping ((Object) -> (T) -> Void)) {
let block = Self.weakify(obj, method: method)
runOnMain { block(parameter) }
}
func runOnMainWeakly<Object: AnyObject>(_ obj: Object,
method: @escaping ((Object) -> () -> Void)) {
let block = Self.weakify(obj, method: method)
runOnMain(block)
}
}
extension MainThreadRunnerType where Self: AnyObject {
func runOnMainWeakly<T>(method: @escaping ((Self) -> (T) -> Void),
parameter: T) {
let block = Self.weakify(self, method: method)
runOnMain { block(parameter) }
}
func runOnMainWeakly(method: @escaping ((Self) -> () -> Void)) {
let block = Self.weakify(self, method: method)
runOnMain(block)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment