【问题标题】:Memory leak when using CombineLatest in Swift Combine在 Swift Combine 中使用 CombineLatest 时的内存泄漏
【发布时间】:2020-08-02 00:35:37
【问题描述】:

我正在使用 Redux 模式来构建消息传递应用程序。到目前为止一切正常,但后来我注意到应用程序的某些部分存在我无法解决的内存泄漏。我的视图控制器绑定到消息发布者。关闭视图控制器时不会调用 Deinit。

        let messages = {
            store.$state
                .map { $0.chatState.messagesByChannel[self.channelId] }
                .removeDuplicates()
                .eraseToAnyPublisher()
        }()

        messages.combineLatest(Just("Hello world"))
            .sink { [weak self] (messages, state) in

        }
        .store(in: &cancellableSet)

当我从引用字典对象更改为聊天状态下的另一个对象时,deinit 被调用

        let chatRoomDetailResponse = {
            store.$state
            .map { $0.chatState.getChatRoomDetailResponse }
                .removeDuplicates()
                .eraseToAnyPublisher()
        }()

        chatRoomDetailResponse.combineLatest(Just("Hello world"))
            .sink { [weak self] (messages, state) in

        }
        .store(in: &cancellableSet)

这是我商店的小快照:

final public class Store<State: FluxState>: ObservableObject {
    @Published public var state: State

    private var dispatchFunction: DispatchFunction!
    private let reducer: Reducer<State>

还有我的聊天状态:


public struct ChatState: FluxState {

    public typealias ChannelID = String

    public var messagesByChannel: [ChannelID: [Message]] = [:]

    public var getChatRoomDetailResponse: NetworkResponse<ChatChannel>? = nil
}

【问题讨论】:

    标签: swift redux memory-leaks combine


    【解决方案1】:

    $0.chatState.messagesByChannel[self.channelId] 强烈捕获self,以便能够访问其最新的channelId 值。

    要么虚弱地捕捉自我:

    .map { [weak self] in 
        guard let strongSelf = self else  { return ??? }
        $0.chatState.messagesByChannel[strongSelf.channelId]
    }
    

    或者如果channelId没有变化,可以使用捕获列表按值捕获:

    .map { [channelId] in $0.chatState.messagesByChannel[channelId] }
    

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 2020-08-07
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 2020-03-19
      • 2022-07-14
      • 2021-03-19
      相关资源
      最近更新 更多