Created
June 21, 2021 19:05
-
-
Save yakushevichsv/8460d239553857592cc72bb0b0362f08 to your computer and use it in GitHub Desktop.
Extension of MainThreadRunnerType For Weakly Calling Block
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
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