Resolving Data Race in iOS Swift
Asked Answered
P

1

5

I have NetworkProvider which will make api call continuously and also once I received the data i will update the userid. At the same time I will access the userid from other functions.

This is data race condition, can someone help to remove the condition.

`

class NetworkProvider  {
   public var userID: String

   func observeStateChange() {

        FIRAuth.auth()?.addStateDidChangeListener({ (auth, authenticatedUser) in
          if let user = authenticatedUser {
              userID = user.uid
          }
       }
    }

   func currentUserID() -> String {
        return self.userID
  }
}`
Pickaback answered 25/9, 2017 at 21:42 Comment(1)
So... how do you want it to behave if another function tries to access the userID before it's ready?Spanishamerican
B
6

Use DispatchQueue can avoid data race:

class NetworkProvider  {
    let isolationQueue = DispatchQueue(label: "com.your.domain.xxx", attributes: .concurrent)
    private var _userID: String
    public var userID: String {
        set { isolationQueue.async(flags: .barrier) { self._userID = newValue } }        
        get { return isolationQueue.sync { _userID } }
    }

    func observeStateChange() {

        FIRAuth.auth()?.addStateDidChangeListener({ (auth, authenticatedUser) in
            if let user = authenticatedUser {
                userID = user.uid
            }
        }
    }

    func currentUserID() -> String {
        return self.userID
    }
}
Beginning answered 18/4, 2018 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.