Skip to content

Commit 75e846e

Browse files
Publishers send the latest shared value for new subscriptions. Fixes #160. (#161)
Co-authored-by: Stephen Celis <[email protected]>
1 parent 5e2b8e4 commit 75e846e

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

Sources/Sharing/SharedPublisher.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
/// }
1616
/// ```
1717
public var publisher: some Publisher<Value, Never> {
18-
box.subject
19-
.handleEvents(receiveSubscription: { [box] _ in _ = box })
20-
.prepend(wrappedValue)
18+
Just<Void>(()).flatMap { _ in
19+
box.subject.prepend(wrappedValue)
20+
}
2121
}
2222
}
2323

@@ -35,9 +35,9 @@
3535
/// }
3636
/// ```
3737
public var publisher: some Publisher<Value, Never> {
38-
box.subject
39-
.handleEvents(receiveSubscription: { [box] _ in _ = box })
40-
.prepend(wrappedValue)
38+
Just<Void>(()).flatMap { _ in
39+
box.subject.prepend(wrappedValue)
40+
}
4141
}
4242
}
4343
#endif

Tests/SharingTests/PublisherTests.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,5 +184,34 @@
184184

185185
#expect(counts.withLock(\.self) == [0, 1, 2, 3])
186186
}
187+
188+
@Test func newSubscribersReceiveLatestValue() async throws {
189+
@Shared(value: "initial") var value
190+
let publisher = $value.publisher
191+
192+
let firstSubscriberValues = Mutex<[String]>([])
193+
194+
let firstCancellable = publisher.sink { completion in
195+
Issue.record()
196+
} receiveValue: { @Sendable value in
197+
firstSubscriberValues.withLock { $0.append(value) }
198+
}
199+
defer { _ = firstCancellable }
200+
201+
$value.withLock { $0 = "latest" }
202+
#expect(firstSubscriberValues.withLock(\.self) == ["initial", "latest"])
203+
204+
let secondSubscriberValues = Mutex<[String]>([])
205+
206+
let secondCancellable = publisher.sink { completion in
207+
Issue.record()
208+
} receiveValue: { @Sendable value in
209+
secondSubscriberValues.withLock { $0.append(value) }
210+
}
211+
defer { _ = secondCancellable }
212+
213+
$value.withLock { $0 = "next" }
214+
#expect(secondSubscriberValues.withLock(\.self) == ["latest", "next"])
215+
}
187216
}
188217
#endif

0 commit comments

Comments
 (0)