Asynchronous loaded Image is not reusable inside the same view

Viewed 405

I have a problem with the asyncimage.

Here is the link to the files https://www.vadimbulavin.com/asynchronous-swiftui-image-loading-from-url-with-combine-and-swift/

The image of the bottom bar does not change on button action. How could I fix it and could you explain it?

podcastIndex is @Publisched inside the PodcastParser Class

The text changes and it's no problem, but the image is alway the same.

Here is my ContentView:

struct ContentView: View {

@ObservedObject var podcastParser = PodcastParser()

init() {
    podcastParser.loadData()
}

var body: some View {
    NavigationView {
        List(podcastParser.podcasts.indices) { index in
            HStack {
                Button(action: {
                    podcastParser.podcastIndex = index
                    print(podcastParser.podcasts[podcastParser.podcastIndex].imageUrl)
                }) {
                    HStack {
                        AsyncImage(
                            url: podcastParser.podcasts[index].imageUrl,
                            placeholder: {
                                Text("Loading...")
                            },
                            image: { Image(uiImage: $0).resizable() }
                        )
                        .scaledToFit()
                        .frame(width: 50, height: 50)
                        Text(podcastParser.podcasts[index].name)
                    }
                }
            }
        }
    }
    VStack {
        HStack {
            AsyncImage(
                url: podcastParser.podcasts[podcastParser.podcastIndex].imageUrl,
                placeholder: {
                    Text("Loading...")
                },
                image: { Image(uiImage: $0).resizable() }
            )
            .scaledToFit()
            .frame(width: 50, height: 50)
            Text(podcastParser.podcasts[podcastParser.podcastIndex].name)
        }
    }
}
}
1 Answers

Generally when you have such problems, there's always a brute force solution to force view update using id modifier.

AsyncImage(
    url: podcastParser.podcasts[podcastParser.podcastIndex].imageUrl,
    placeholder: {
        Text("Loading...")
    },
    image: { Image(uiImage: $0).resizable() }
).id(podcastParser.podcasts[podcastParser.podcastIndex].imageUrl)

With system AsyncImage this would be the only solution, but in your case you're using open source solition, so can modify it to fix the problem.

Replacing StateObject with ObservedObject in AsyncImage.swift solves the problem in this case. I'm using same approach with this library and haven't faced any issues so far.

Related