iOS Swift Combine: cancel a Set

后端 未结 5 2117
醉梦人生
醉梦人生 2021-01-11 09:52

If I have stored a cancellable set into a ViewController:

private var bag = Set()

Which contains multiple subscription.

5条回答
  •  一个人的身影
    2021-01-11 10:19

    if you happened to subscribe to a publisher from your View controller, likely you will capture self in sink, which will make a reference to it, and won't let ARC remove your view controller later if the subscriber didn't finish, so it's, advisable to weekly capture self


    so instead of:

       ["title"]
          .publisher
          .sink { (publishedValue) in
            self.title.text = publishedValue
        }
    
    .store(in: &cancellable)
    

    you should do:

       ["title"]
          .publisher
          .sink { [weak self] (publishedValue) in
            self.title.text = publishedValue
        }
    
    .store(in: &cancellable)
    

    thus, when View controller is removed, you won't have any retain cycle or memory leaks.

提交回复
热议问题