0

I'm using Rxswift to design ViewModel. Below is the code that I wrote. In my first map operator used [weak self] and used guard to unwrap the value.

What I realized is 'self' that I unwrapped in first map is still available in second map and in all other operators below.

But I'm not quite sure why unwrapped self in first map operator is still available in operator below and whether there will be problems when using it in other operators

let textObservable = input.subject
      .map { [weak self] _ -> [String] in
          guard let self = self else { return [] }
          return [$0]
       }.map { maps in
          maps.map { text -> String in
              return self.makeString(string: text)
          }
       }
NewBie
  • 7
  • 2
  • 1
    Since you explicitly reference `self` with `self.makeString(string: text)` in `maps.map { ... }` closure it's capturing strong self reference. It doesn't care about the `[weak self]` in previous map closure. Rx is irrelevant here. – Kamil.S Nov 10 '21 at 16:54
  • What's the question here? – Daniel T. Nov 11 '21 at 01:10

1 Answers1

0

But I'm not quite sure why unwrapped self in first map operator is still available in operator below and whether there will be problems when using it in other operators

The unwrapped self is not available in the operator below. You are making a new retain of self in the second closure.

Yes, there will likely be problems. If you are storing the cancellable in the object represented by self (which is the normal practice) then you have setup a retain cycle and the memory for self will never be released...

Daniel T.
  • 32,821
  • 6
  • 50
  • 72