BaseViewModel to observe DRY precept in iOS utilizing Swift

0
17
BaseViewModel to observe DRY precept in iOS utilizing Swift


I’m coming from Android world the place now we have summary class. I’m attempting to enhance in iOS utilizing Swift. I create a base class as observe :

class BaseViewModel: ObservableObject {
    typealias GHError = APIService.GHError
    
    @Revealed var consequence = Useful resource.loading
    
    let apiService = APIService()
    
    init() {
        refresh()
    }
    
    func getSuccessResult() async throws -> T? {
        return nil
    }
    
    func refresh() {
        consequence = Useful resource.loading
        Activity { @MainActor in
            do {
                if let successResult = strive await getSuccessResult() {
                    consequence = Useful resource.success(successResult)
                }
            } catch GHError.invalidURL {
                consequence = Useful resource.error("Invalid URL")
            } catch GHError.invalidResponse {
                consequence = Useful resource.error("Invalid response")
            } catch GHError.invalidData {
                consequence = Useful resource.error("Invalid knowledge")
            } catch {
                consequence = Useful resource.error("Sudden error")
            }
        }
    }
    
    enum Useful resource {
        case loading
        case success(T)
        case error(String)
    }
}

I’m attempting to keep away from writing refresh methodology in each ViewModel I create, so that’s the reason I created the bottom, and as we shouldn’t have summary in Swift, I add this methodology which return nil in base class :

func getSuccessResult() async throws -> T? {
     return nil
}

Right here is an instance of sub viewModel :

class GithubViewModel : BaseViewModel<[UserWrapper]> {
    
    override func getSuccessResult() async throws -> [UserWrapper] {
        async let following = apiService.getUsers(endPoint: Constants.followingEndPoint)
        async let followers = apiService.getUsers(endPoint: Constants.followersEndPoint)
        return strive await UserWrapper.createUsers(following: following, followers: followers)
    }
    
    personal struct Constants {
        personal static let endPoint = "https://api.github.com/customers/alirezaeiii/"
        static let followingEndPoint = endPoint + "following"
        static let followersEndPoint = endPoint + "followers"
    }
}

It really works tremendous however I’m not certain if I’m following an excellent strategy to observe DRY (do not repeat your self) precept.

Would you assist me out together with your remark if there’s any enchancment.

supply code is right here : https://github.com/alirezaeiii/Github-Customers-Task/tree/most important

LEAVE A REPLY

Please enter your comment!
Please enter your name here