I have implemented a simple MVVM binding using closures in UIKit. Is it the actual way to do it. Here is my code. In SwiftUI I use @Published but in UIKit is there any equivalent available to implement MVVM binding
class CardSearchViewModel{
var cardData = [Datum]()
var isPagination: Bool = false
var onCardDataChange: ((Error?) -> Void)?
func searchCard(name: String,pageCount: Int){
if isPagination{
return
}
isPagination = true
Task{
let result = await NetworkService().sendGETRequest(url: "https://api.pokemontcg.io/v2/cards?q=\(name)&page=\(pageCount)&pageSize=20", type: Welcome.self)
switch result{
case .success(let response):
if let data = response.data{
print(data)
self.cardData.append(contentsOf: data)
if data.isEmpty{
isPagination = true
}
else{
isPagination = false
}
onCardDataChange?(nil)
}
break
case .failure(let error):
print(error)
self.isPagination = false
onCardDataChange?(error)
break
}
}
}
func getCardsBySet(name: String,setId: String,pageCount: Int){
if isPagination{
return
}
self.isPagination = true
Task{
let result = await NetworkService().sendGETRequest(url: "https://api.pokemontcg.io/v2/cards?q=\(name)set.id:\(setId) &pageSize=25&page=\(pageCount)", type: Welcome.self)
switch result{
case .success(let response):
if let data = response.data{
print(data)
self.cardData.append(contentsOf: data)
if data.isEmpty{
self.isPagination = true
}
else{
self.isPagination = false
}
onCardDataChange?(nil)
}
break
case .failure(let error):
print(error)
self.isPagination = false
onCardDataChange?(error)
break
}
}
}
}
I use that call back closure to update the UI when the cardData array value is updated after the API call.