Skip to content

Commit

Permalink
Fix resource leak in ReplaySubject (#802)
Browse files Browse the repository at this point in the history
Co-authored-by: Samuel Défago <[email protected]>
  • Loading branch information
waliid and defagos authored Mar 13, 2024
1 parent 5b48717 commit edfcb80
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Sources/Core/ReplaySubject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import Foundation
/// any relevant completion.
public final class ReplaySubject<Output, Failure>: Subject where Failure: Error {
private let buffer: LimitedBuffer<Output>
private var subscriptions: [ReplaySubscription<Output, Failure>] = []
private var completion: Subscribers.Completion<Failure>?
private let lock = NSRecursiveLock()
var subscriptions: [ReplaySubscription<Output, Failure>] = []

/// Creates a subject able to buffer the provided number of values.
///
Expand Down Expand Up @@ -54,6 +54,10 @@ public final class ReplaySubject<Output, Failure>: Subject where Failure: Error
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
withLock(lock) {
let subscription = ReplaySubscription(subscriber: subscriber, values: buffer.values)
subscription.onCancel = { [weak self] in
guard let self else { return }
subscriptions.removeAll { $0 === subscription }
}
buffer.values.forEach { value in
subscription.append(value)
subscription.send()
Expand Down
4 changes: 4 additions & 0 deletions Sources/Core/ReplaySubscription.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Combine
import Foundation

final class ReplaySubscription<Output, Failure>: Subscription where Failure: Error {
var onCancel: (() -> Void)?

private var subscriber: AnySubscriber<Output, Failure>?
private var buffer = DemandBuffer<Output>()
private var pendingValues: [Output] = []
Expand All @@ -22,6 +24,8 @@ final class ReplaySubscription<Output, Failure>: Subscription where Failure: Err

func cancel() {
subscriber = nil
onCancel?()
onCancel = nil
}

func append(_ value: Output) {
Expand Down
9 changes: 9 additions & 0 deletions Tests/CoreTests/ReplaySubjectTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ final class ReplaySubjectTests: XCTestCase {
expectEqualPublished(values: [2, 3], from: subject, during: .milliseconds(100))
}

func testSubscriptionRelease() {
let subject = ReplaySubject<Int, Never>(bufferSize: 1)
subject.send(1)

_ = subject.sink { _ in }

expect(subject.subscriptions).to(beEmpty())
}

func testNewValuesWithMultipleSubscribers() {
let subject = ReplaySubject<Int, Never>(bufferSize: 2)
subject.send(1)
Expand Down

0 comments on commit edfcb80

Please sign in to comment.