SwiftUI-Combine icon indicating copy to clipboard operation
SwiftUI-Combine copied to clipboard

.assign(to:, on: self) creates a memory leak

Open utilem opened this issue 3 years ago • 0 comments

Instead of using:

  isUsernameValidPublisher
          .receive(on: RunLoop.main)
          .map { valid in
              valid ? "" : "User name must at least have 3 characters"
          }
           .assign(to: \.usernameMessage, on: self)
          .store(in: &cancellableSet)

which ends in a retain cycle, it's better to use [weak self] with .sink

  isUsernameValidPublisher
          .receive(on: RunLoop.main)
          .map { valid in
              valid ? "" : "User name must at least have 3 characters"
          }
          .sink(receiveValue: { [weak self] string in
              self?.usernameMessage = string
          })
          .store(in: &cancellableSet)

utilem avatar Oct 16 '22 05:10 utilem