Skip to content

Instantly share code, notes, and snippets.

@MMnasrabadi
Last active April 28, 2021 10:58
Show Gist options
  • Save MMnasrabadi/955bfb0ea979ddeb01f4418adafa0e05 to your computer and use it in GitHub Desktop.
Save MMnasrabadi/955bfb0ea979ddeb01f4418adafa0e05 to your computer and use it in GitHub Desktop.
// clean remore memory leak
protocol Weakifiable: class { }
extension NSObject: Weakifiable {}
extension Weakifiable {
func weakify<T, Z>(_ code: @escaping (Self, T) -> Z) -> (T) -> Z? {
return { [weak self] data in
guard let self = self else { return nil}
return code(self, data)
}
}
func weakify<T>(_ code: @escaping (Self, T) -> Void) -> (T) -> Void {
return { [weak self] data in
guard let self = self else { return }
code(self, data)
}
}
func weakify<Z>(_ code: @escaping (Self) -> Z) -> () -> Z? {
return { [weak self] in
guard let self = self else { return nil}
return code(self)
}
}
func weakify(_ code: @escaping (Self) -> Void) -> () -> Void {
return { [weak self] in
guard let self = self else { return }
code(self)
}
}
}
@MMnasrabadi
Copy link
Author

MMnasrabadi commented Jan 6, 2021

  • old use weak:
    var returnCellText: (String) -> ()

      var returnCellText: (String) -> () = { data in
          // use self but have memory leak
      }
      
      var returnCellText: (String) -> () = { [weak self] data in
          guard let self = self else { return }
          // use self
      }
    
  • use weakify

      var a: (String) -> () = weakify { (vc, data) in
          
      }
    

-- or

    .subscribe(onNext: weakify { (vc, loading) in
        vc.creditCardDataSource.comingLoadingData = loading
    })

// instead of

   .subscribe(onNext: { [weak self] loading in
        guard let self = self else { return }
        self.creditCardDataSource.comingLoadingData = loading
   })

@MMnasrabadi
Copy link
Author

  • in RxSwift 6.0.0 use
    .withUnretained(self)
    auto weakify by rx

@MMnasrabadi
Copy link
Author

  • in weakify by return :
    use .CompactMap instead of .map
    because is optional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment