Home > Software design >  Using Alamofire in MVVM and wrapping in Async (iOS, Swift)
Using Alamofire in MVVM and wrapping in Async (iOS, Swift)

Time:01-28

I was trying to wrap Alamofire with async, but the answers that I found couldn't help me, but after finding the solution, I thought that I should help some one with this same problem.

Following a very decoupled MVVM project, my DataLayer was outside from the ViewModel Layer, so I couldn't let the AF.request handler the Diffable direct. So my solution was wraping the @escaping with withCheckedContinuation

CodePudding user response:

There's no need to wrap Alamofire for async / await, it already offers a native version of that API.

let response = await AF.request(...).serializingDecodable(<YourType>.self)

You can also await .result and try await .value on the above to access the parts you need.

CodePudding user response:

DataLayer.swift:

func fetchRequests() async -> [MyModel] {
        await withCheckedContinuation{ continuation in
            downloadJson{ models in
                continuation.resume(returning: models)
        }
    }
}

private func downloadJson(completion: @escaping ([MyModel]) -> Void){
        let url = "https://......"
        AF.request(url).responseDecodable(of: [MyModel].self){ response in
            guard let models = response.value else {return}
            completion(models)
        }
    }

ModelModule.swift:

var data: [MyModel]

function loadData() async {
    data = await dataLayer.fetchRequests()
}

Finally the ViewModel.swift:

func configure(dataSource: AnyDiffableDataSource<MySection, MyModelItem>) {
        self.dataSource = dataSource
        
        Task {
            await modelModule.loadData()
            dataSource.create(sections: [.main], animated: true)
            updateDateSource(animated: true)
            //... rest of the configuration
        }
    }
  • Related