gpt4 book ai didi

swift - 发布者完成后从 AnyCancellable 数组中删除

转载 作者:行者123 更新时间:2023-12-03 21:58:58 25 4
gpt4 key购买 nike

是否有处理 AnyCancellable 数组的好方法?删除存储的 AnyCancellable什么时候完成/取消?

说我有这个

import Combine
import Foundation

class Foo {

private var cancellables = [AnyCancellable]()

func startSomeTask() -> Future<Void, Never> {
Future<Void, Never> { promise in
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
promise(.success(()))
}
}
}

func taskCaller() {
startSomeTask()
.sink { print("Do your stuff") }
.store(in: &cancellables)
}

}

每次 taskCaller被称为 AnyCancellable创建并存储在数组中。
我想在它完成时从数组中删除该实例以避免内存浪费。

我知道我可以做这样的事情,而不是数组
var taskCancellable: AnyCancellable?

并通过执行以下操作存储可取消项:
taskCancellable = startSomeTask().sink { print("Do your stuff") }

但是这样会结束创建多个单一的cancellable并且会污染代码。我不想要这样的类(class)
class Bar {

private var task1: AnyCancellable?
private var task2: AnyCancellable?
private var task3: AnyCancellable?
private var task4: AnyCancellable?
private var task5: AnyCancellable?
private var task6: AnyCancellable?

}

最佳答案

我在开发一个应用程序时问自己同样的问题,该应用程序会生成大量最终存储在同一数组中的可取消项。对于长期存在的应用程序,数组大小可能会变得很大。
即使内存占用很小,那些仍然是对象,它们消耗堆,这会导致堆碎片及时。
我找到的解决方案是在发布者完成后删除可取消的:

func consumePublisher() {
var cancellable: AnyCancellable!
cancellable = makePublisher()
.sink(receiveCompletion: { [weak self] _ in self?.cancellables.remove(cancellable) },
receiveValue: { doSomeWork() })
cancellable.store(in: &cancellables)
}
确实,代码不是那么漂亮,但至少没有内存浪费:)
一些高阶函数可用于使此模式可在同一类的其他地方重用:
func cleanupCompletion<T>(_ cancellable: AnyCancellable) -> (Subscribers.Completion<T>) -> Void {
return { [weak self] _ in self?.cancellables.remove(cancellable) }
}

func consumePublisher() {
var cancellable: AnyCancellable!
cancellable = makePublisher()
.sink(receiveCompletion: cleanupCompletion(cancellable),
receiveValue: { doSomeWork() })
cancellable.store(in: &cancellables)
}
或者,如果您需要支持以完成工作:
func cleanupCompletion<T>(_ cancellable: AnyCancellable) -> (Subscribers.Completion<T>) -> Void {
return { [weak self] _ in self?.cancellables.remove(cancellable) }
}

func cleanupCompletion<T>(_ cancellable: AnyCancellable, completionWorker: @escaping (Subscribers.Completion<T>) -> Void) -> (Subscribers.Completion<T>) -> Void {
return { [weak self] in
self?.cancellables.remove(cancellable)
completionWorker($0)
}
}

func consumePublisher() {
var cancellable: AnyCancellable!
cancellable = makePublisher()
.sink(receiveCompletion: cleanupCompletion(cancellable) { doCompletionWork() },
receiveValue: { doSomeWork() })
cancellable.store(in: &cancellables)
}

关于swift - 发布者完成后从 AnyCancellable 数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60685810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com