Skip to main content

Swift - Quá nhiều Model quá nhiều request function. Khỏi lo đã có Generics


Và hôm nay mình sẽ giới thiệu một vấn đề thực tế gặp phải khi mới học swift đó là khi lấy data từ các API về và Model của các data đó không giống nhau.
Trong bài này API được mượn tạm từ https://openweathermap.org/triggers.
1:https://samples.openweathermap.org/data/3.0/stations?appid=b1b15e88fa797225412429c1c50c122a1
2:https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
Mình sẽ đổ dữ liệu lấy từ 2 API trên vào view.

Bắt đầu

API 1: là 1 array như trong hình

API2:

Tạo một Project demo có 2 view. Trong các view có chứa các label như sau.
View trên mình lấy thông tin id, name, external_id trong API số 1 sau khi tap vào button..
Tương tự như view trên, View dưới mình lấy thông tin id, name, cod từ API số 2 sau khi tap.

Model

Tạo ra 2 model tương ứng với 2 kiểu dữ liệu trong 2 API.
Trong API rất nhiều key nhưng vì trong demo này mình chỉ dùng có 3 key trong API nên Model sẽ có dạng như sau.
struct Model1: Codable {
    var id: String?
    var name: String?
    var external_id: String?
}

struct Model2: Codable {
    var id: Int?
    var name: String?
    var cod: Int?
}

Request

Ứng với mỗi một API mình tạo ra 1 request lấy data và đổ ra view như sau.
Đối với view1
@objc private func didTap1() {
//Sau khi tap vào button ở view1 sẽ thực hiện request lấy data, sau đó update view
        requestData1(urlString: urlStr1) { (model1Data) in
            self.updateView1(by: model1Data)
        }
    }
    
    private func requestData1(urlString: String, completion:@escaping (Model1)->()) {
        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error as Any)
                return
            }
            guard let data = data else { return }
            do {
                let model1Data = try JSONDecoder().decode(Model1.self, from: data)
                DispatchQueue.main.async {
                    completion(model1Data)
                }
            } catch let err {
                print("decode error: ", err)
            }
        }.resume()
    }
    
    private func updateView1(by model: Model1) {
        let id = model.id ?? "no have id"
        let name = model.name ?? "no have name"
        let externalID = model.external_id ?? "no have external ID"
        lbl1.text = id
        lbl2.text = name
        lbl3.text = externalID
    }
Kết quả

Tương tự đối với view2
@objc private func didTap2() {
        requestData2(urlString: urlStr2) { (model2Data) in
            self.updateView2(by: model2Data)
        }
    }
    
    private func requestData2(urlString: String, completion:@escaping (Model2)->()) {
        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error as Any)
                return
            }
            guard let data = data else { return }
            do {
                let model2Data = try JSONDecoder().decode(Model2.self, from: data)
                DispatchQueue.main.async {
                    completion(model2Data)
                }
            } catch let err {
                print("decode error: ", err)
            }
        }.resume()
    }
    
    private func updateView2(by model: Model2) {
        let id = model.id ?? 0
        let name = model.name ?? "no have name"
        let cod = model.cod ?? 0
        v2lbl1.text = "ID: \(id)"
        v2lbl2.text = "name: \(name)"
        v2lbl3.text = "cod: \(cod)"
    }

Vấn đề

Vậy chuyện gì sẽ sảy ra nếu bạn phải làm việc với 296 Models khác nhau. Tất nhiên là việc viết 296 request function cũng khả thi nhưng nó tốn khá nhiều công sức và bảo trì cũng mất công nữa.

Generic is 神

Đúng, chính nó. Thay vì định nghĩa từng kiểu dữ liệu trả về của từng request thì đưa vào một kiểu dữ liệu chung nhất cho tất cả các request sẽ giúp bạn tiết kiệm được rất nhiều thời gian.

Thực hành

Tự tin xoá 2 function requestData bên trên và bắt đầu cùng generic thôi anh em.
//một function có chứa generic type sẽ có kiểu như này.
private func getData<T: Codable>(urlString: String, completion:@escaping (T)->()) {
        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error as Any)
                return
            }
            guard let data = data else { return }
            do {
                let data = try JSONDecoder().decode(T.self, from: data)
                DispatchQueue.main.async {
                    completion(data)
                }
            } catch let err {
                print("decode error: ", err)
            }
        }.resume()
    }
Sử dụng
Các bạn đã thấy sự khác biệt chưa
Mỗi lần tap button thì function getData() được gọi. Và bạn chỉ cần định nghĩa kiểu dữ liệu muốn sử dụng là xong. Chứ không như function requestData bên trên, kiểu dự liệu không thể thay đổi.
@objc private func didTap1() {
        getData(urlString: urlStr1) { (model1Data: Model1) in
            self.updateView1(by: model1Data)
        }
    }
    
    @objc private func didTap2() {
        getData(urlString: urlStr2) { (model2Data: Model2) in
            self.updateView2(by: model2Data)
        }
    }

Kết

Cho dù bạn làm việc với 19999 Model khác nhau thì cũng cuối ngày mặt vẫn tươi như hoa vì đã có generic =))
Code ngắn đi nhiều và cực kỳ dễ bảo trì.
https://github.com/nguyentienhoang810/generis-demo

Comments

Popular posts from this blog

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Thread safe singleton’s in Swift

What are singletons? — Singleton is design patterns which says that there should be only one instance of the class for the lifetime of the application. One the best example of Singleton is AppDelegate . How to write a singleton class ? class DefaultDict{ private var dict:[String:Any] = [:] public static let sharedManager = DefaultDict() private init(){ } public func set(value:Any,key:String){ dict[key] = value } public func object(key:String) -> Any?{ dict[key] } public func reset(){ dict.removeAll() } }   Testing singleton class under concurrent circumstances. We are going to write an example where we will set values in dict from various threads and even try to access some with different threads. When we do this we will encounter a crash. If you look closely it will be because of race condition and the crash will be on line set(value:Any,key:String) . class ViewController: UIViewController { ...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...