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

RxSwift - Giới thiệu

Bạn có nghe qua về Reactive Programming chưa, đây là một khái niệm lập trình hoàn toàn mới. “Reactive Programming là lập trình theo hướng bất đồng bộ các dòng chảy dữ liệu(data streams)” Sau khi đọc khái niệm các bạn có lẽ rất mơ hồ, vậy các data streams là gì. Vậy để mình ví dụ cho các bạn: - Trong lập trình bình thường ( imperative programming ) a = b + c , tức a được gắn với kết quả cộng của b và c .Khi b với c thay đổi thì tất nhiên sẽ không ảnh hưởng tới a, nhưng trong Reactive Programming này a sẽ tự động thay đổi khi b hoặc c thay đổi, kết quả của a sẽ lập tức thay đổi theo. Vậy tại sao nên dùng RXSwift: + Giúp ứng dụng của bạn hoạt động 1 cách như là real time update ui khi có thay đổi data flow, mang đến trải nghiệm tuyệt vời cho User. + Dễ dàng lập trình bất đồng bộ (Async) thay vì phải dùng : callbacks, delegates, notifications, kvo… Bạn phải dùng nhiều thứ gây ra ứng dụng của bạn phức tạp, khó kiểm soát. + Chuyển đổi các thread khi thực hiện 1 cách...

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...

Enum Initializers

In Swift Talk 45 , we wrote a small library for parsing routes. We represented routes as enums, and added a custom initializer to parse routes: enum Route { case home case users(id: Int ) } extension Route { init ?(path: String ) { if path == "/" { self = .home } else if path.hasPrefix( "/users" ) { self = .users(id: 1 ) } else { return nil } } } Of course, this code isn’t complete (see the full public episode for that). Today, we want to focus on assigning to self inside the initializer. In the initializer of any struct or enum we can treat self as a mutable variable (as if it were declared using inout ). This is why we can do the following: enum Result < A > { case success( A ) case error( Error ) } extension Result { init ( _ value: A ) { self = .success(value) } } We can even do this in a struct, although it’s easie...