Hi,
I have been working one thing for whole day, and figured out something odd.
I am fetching my data via API. then wanna show in a horizontal scroll view. Using ObservableObject and ObservedObject.
Problem: View doesn’t update when fetching has been done. I need to click the view and it refreshes with my content.
Odd part of it, If I use only List instead of scrollview then there isn’t any problem. It refreshes perfectly.
Not sure this is a bug or I am missing something.
Code below:
class HomeViewModel: ObservableObject {
private var subscriptions = Set<AnyCancellable>()
@Published private var companies = [Company]()
var allCompanies: [Company] {
return companies
}
func start() {
ApolloNetwork().send(GetAllCompaniesQuery())
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { _ in }) { result in
self.companies = result.companies.map {
Company(name: $0.name!, graphQLId: $0.id!)
}
}
.store(in: &subscriptions)
}
}
View
struct ContentView: View {
@ObservedObject var viewModel: HomeViewModel
init(viewModel: HomeViewModel) {
self.viewModel = viewModel
}
var body: some View {
NavigationView {
// 1 - This part not refreshing unless it is interacted with view then it refreshes.
List{
ScrollView(.horizontal) {
HStack {
ForEach(viewModel.allCompanies){ company in
NavigationLink(destination: CompanyProfileView()) {
CompanyView(company: company)
}
}
}
}
}.navigationBarTitle(Text("Home"))
/*
// 2- Comment part 1 and uncomment this part. WORKS WELL
List(viewModel.allCompanies) { company in
NavigationLink(destination: CompanyProfileView()) {
CompanyView(company: company)
}
}
*/
}
}
}
ScrollView Shots
First picture, fetching done but didn’t refresh, did tap on the screen then refreshed.
List only shot fetch done refreshed immediately.
Thanks
Selcuk