简体   繁体   English

从 actor 中的 operationQueue 发布 operationCount?

[英]Publish `operationCount` from operationQueue inside actor?

I have an actor:我有一个演员:

actor MyActor {
    
    let theQueue = OperationQueue()

    init() {

        _ = theQueue.observe(\OperationQueue.operationCount, options: .new) { oq, change in
            print("OperationQueue.operationCount changed: \(self.theQueue.operationCount)")
        }
        
    }

    ....

}

I was trying to get a KVO going to then trigger some type of publisher call that other models in the app could subscribe to and react as needed when the operationCount changes.我试图让 KVO 去触发某种类型的发布者调用,应用程序中的其他模型可以订阅并在 operationCount 更改时根据需要做出反应。

I was going to have a function that maybe would set that up, but, as of now, using self in that initializer gives me this warning, which according this this:我打算有一个 function 可能会设置它,但是,截至目前,在该初始化程序中使用self会给我这个警告,根据这个:

https://forums.swift.org/t/proposal-actor-initializers-and-deinitializers/52322 https://forums.swift.org/t/proposal-actor-initializers-and-deinitializers/52322

it will turn into an error soon.它很快就会变成错误。

The warning I get is this:我得到的警告是这样的:

Actor 'self' can only be captured by a closure from an async initializer Actor“self”只能被异步初始化器的闭包捕获

So, how could I trigger a publisher other models can then react to that would publish the operation queue's operationCount as it changes?那么,我如何触发一个发布者,然后其他模型可以对此做出反应,从而在操作队列的operationCount发生变化时发布它?

You don't need to capture self here.你不需要在这里捕获self observe sends you the new value (for basically exactly this reason): observe向您发送新值(基本上就是这个原因):

_ = theQueue.observe(\OperationQueue.operationCount, options: .new) { oq, change in
    print("OperationQueue.operationCount changed: \(change.newValue!)")
}

Also, oq is theQueue if you need that.另外,如果需要, oqtheQueue If you need self , the typical way to do that is:如果你需要self ,典型的方法是:

observation = observe(\.theQueue.operationCount, options: .new) { object, change in
    // object is `self` here.
}

Just remember that you're outside the actor inside this closure, so calls may need to be async inside a Task.请记住,您在这个闭包内的 actor 之外,因此调用可能需要在 Task 内异步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM