Skip to content

Commit

Permalink
Make sure not to display an image that belongs to a different post
Browse files Browse the repository at this point in the history
The key change here is to store the image subscription in the MediaView’s disposeBag rather than the configuration’s, so that it is properly disposed of in the MediaView’s prepareForReuse().

For good measure, also adding MainActor on prepareForReuse and actual cancellation of all subscriptions before releasing them.

Fixes #1374 [BUG] Posts can load the wrong images
  • Loading branch information
whattherestimefor committed Dec 10, 2024
1 parent 9e24af5 commit ca6ecd1
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions MastodonSDK/Sources/MastodonUI/View/Content/MediaView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,25 @@ extension MediaView {
layoutAlt()
}

private func bindImage(configuration: Configuration, info: Configuration.ImageInfo) {
private func bindImage(configuration: Configuration, info: Configuration.ImageInfo) {
let subscribedConfigurationIdentifier = ObjectIdentifier(configuration) // this shouldn't be necessary now, but allows a check in debug mode. https://github.com/mastodon/mastodon-ios/issues/1374
Publishers.CombineLatest(
configuration.$previewImage,
configuration.$blurhashImage
)
.receive(on: DispatchQueue.main)
.sink { [weak self] previewImage, blurhashImage in
guard let self = self else { return }

guard let currentConfiguration = self.configuration, ObjectIdentifier(currentConfiguration) == subscribedConfigurationIdentifier else {
assert(false, "\(self) attempt to load an image that belongs to a configuration no longer associated with this MediaView.")
return
}
let image = configuration.isReveal ?
(previewImage ?? blurhashImage ?? MediaView.placeholderImage) :
(blurhashImage ?? MediaView.placeholderImage)
self.imageView.image = image
}
.store(in: &configuration.disposeBag)
.store(in: &_disposeBag)

bindAlt(configuration: configuration, altDescription: info.altDescription)
}
Expand Down Expand Up @@ -220,7 +224,11 @@ extension MediaView {
overlayViewController.view.pinToParent()
}

@MainActor
public func prepareForReuse() {
for cancellable in _disposeBag {
cancellable.cancel()
}
_disposeBag.removeAll()

// reset appearance
Expand Down

0 comments on commit ca6ecd1

Please sign in to comment.