5

我有 NetworkProvider,它将不断地调用 api,并且一旦我收到数据,我将更新用户 ID。同时,我将从其他功能访问用户 ID。

这是数据竞争条件,有人可以帮助删除条件。

`

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
  }
}`
4

1 回答 1

6

使用 DispatchQueue 可以避免数据竞争:

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
    }
}
于 2018-04-18T13:19:34.477 回答