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
  }
}`
venky
  • 1,155
  • 1
  • 11
  • 26
  • So... how do you want it to behave if another function tries to access the userID before it's ready? – Robert Sep 25 '17 at 21:56

1 Answers1

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
    }
}
DàChún
  • 4,751
  • 1
  • 36
  • 39