Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

web calling function using mvvm pattern in swift

Tags:

ios

swift

mvvm

web

I’m trying to implement MVVM design pattern using swift but few things are not clear to me which are mentioned below.

I need to get list of flowers and display it tableview. I will call web api which will give details of different types of Flower. So I created Class Flower (as Model) and FlowerViewModel class as (ViewModel) and ViewController had the tableview in it.

But not sure, in which class should I place the calling of web api and parsing JSON response ? As of now I have both these placed in the FlowerViewModel class

Please suggest if need to do correction for placing of these two functions or my assumption is correct.

Thanks

like image 966
manisha upadhyay Avatar asked Aug 17 '26 01:08

manisha upadhyay


1 Answers

The Web Service API class should be separate following Single Responsibility Principle (SRP) but the caller or the instance of this class should be in view model. ViewModel delegates the service to call the Web API and from the parsed response, it takes the list of flowers binding these items to the UITableView. That is how I am implementing in MVVM.

Making it clear:

class FlowerFetcher {
    func getFlowers(callback: ([Flowers])->()) {}
}

class FlowerViewModel {
    private var flowerService: FlowerFetcher?

    init(flowerService: FlowerFetcher?) {}
}
like image 124
prex Avatar answered Aug 18 '26 17:08

prex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!