0

Lets say I have a struct state like this

struct SomeState: Equatable {
    var counter: Int = 0
    var foo: Bool = false
}

and then a subject of private let _state = CurrentValueSubject(SomeState())

I know I can update it as _state.value.counter += 1

Is this however thread-safe in a concurrent context? Will any write wait for the previous one? Or will there be some state smashing? I'm not sure how this works under the hood in swift, I'm coming from kotlin

urSus
  • 12,492
  • 12
  • 69
  • 89
  • 4
    No, this is not thread safe. Swift makes no guarantees in this case. Put it in an actor or something. – Sweeper Jul 03 '22 at 17:09
  • I had a hunch. Thank you – urSus Jul 03 '22 at 19:22
  • Modifying the value of a `CurrentValueSubject` in this way is a bit odd. The point behind holding the thing in a subject is that you want a new value to be published. Changing the cached instance inside of the `CurrnetValueSubject` breaks its encapsulation. In my opinion, you should reconsider your approach. – Scott Thompson Jul 07 '22 at 17:53
  • I do want it published and it does get published – urSus Jul 08 '22 at 18:12
  • Related: ["PassthroughSubject" seems to be thread-unsafe, is this a bug or limitation?](https://stackoverflow.com/questions/56731802/passthroughsubject-seems-to-be-thread-unsafe-is-this-a-bug-or-limitation) – Cristik Jul 21 '22 at 04:19

0 Answers0