Skip to main content

RxSwift: Clean Architecture, MVVM và RxSwift


I. Giới thiệu:


Ở phần trước, chúng ta đã tìm hiểu qua về Clean Architecture và MVVM. Các bạn có thể xem lại bài viết trước tại đây. Trong bài viết này, mình sẽ đưa ra một example đơn giản về Clean Architecture và MVVM.

II. Demo:


Trong ví dụ này, chúng ta sẽ sử dụng API public của github https://api.github.com/search/repositories
Các param sẽ sử dụng là:
  • q: language:swift
  • per_page: 10
  • page: 1
Source code demo: https://github.com/tgdong2296/SimpleDemoCleanArchitecture

1. Domain:

Trong tầng Domain, chúng ta sẽ chứa những Model là các thành phần cơ bản của ứng dụng. Tất cả các Model nằm trong Domain đều không phụ thuộc vào bất cứ thành phần nào khác của ứng dụng.
import Foundation
import ObjectMapper

protocol BaseModel: Mappable {
    
}
import ObjectMapper
import Then

struct GithubRepo {
    var id = 0
    var name: String
    var fullname: String
    var urlString: String
    var starCount: Int
    var folkCount: Int
    var avatarURLString: String
}

extension GithubRepo {
    init() {
        self.init(
            id: 0,
            name: "",
            fullname: "",
            urlString: "",
            starCount: 0,
            folkCount: 0,
            avatarURLString: ""
        )
    }
}

extension GithubRepo: Then, Hashable {
    
}

extension GithubRepo: BaseModel {
    
    init?(map: Map) {
        self.init()
    }
    
    mutating func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        fullname <- map["full_name"]
        urlString <- map["html_url"]
        starCount <- map["stargazers_count"]
        folkCount <- map["forks"]
        avatarURLString <- map["owner.avatar_url"]
    }
}

2. Platform:

Tại Platform chúng ta sẽ tiến hành triển khai việc gọi API và tiếp nhận data thông qua một Repository. Repository sẽ chịu trách nhiệm thực hiện request tới server và tiếp nhận reponse được trả về từ server, sau đó bóc tách data trong response. APIService sẽ trả về một Observable<GithubRepoResponse> và chúng ta sẽ sử dụng operator .map{ } để bóc tách dữ liệu mà response trả về. Như vậy, mỗi khi request API thành công thì Observable sẽ onNext ra một element có kiểu dữ liệu là [GithubRepo].
import Foundation
import ObjectMapper
import RxSwift

protocol GithubRepoRepositoryType {
    func getGithubRepos(input: GithubRepoRequest) -> Observable<[GithubRepo]>
}

class GithubRepoRepository: GithubRepoRepositoryType {
    private let api: APIService = APIService.share
    
    func getGithubRepos(input: GithubRepoRequest) -> Observable<[GithubRepo]> {
        return api.request(input: input)
            .map { (response: GithubRepoResponse) -> [GithubRepo] in
                return response.githubRepos
            }
    }
}

3. Application:

Đây là tầng mà chúng ta sẽ triển khai mô hình MVVM. Chúng ta sẽ coi các thành phần view nằm trong StoryBoard hoặc Xib và ViewController thuộc lớp View của mô hình MVVM.

3.1. ViewController

ViewController sẽ được adopt một protocol đó là BindableType. Tất cả các UIViewController khi adopt protocol này sẽ phải định nghĩa một property là viewModel chịu trách nhiệm lưu giữ instance của ViewModel trong ViewController và func bindViewModel() để thực hiện binding dữ liệu.
import UIKit
import RxSwift

public protocol BindableType: class {
    associatedtype ViewModelType
    
    var viewModel: ViewModelType! { get set }
    
    func bindViewModel()
}

extension BindableType where Self: UIViewController {
    public func bindViewModel(to model: Self.ViewModelType) {
        viewModel = model
        loadViewIfNeeded()
        bindViewModel()
    }
}
import UIKit
import Foundation
import RxSwift
import RxCocoa
import Then
import NSObject_Rx
import MGArchitecture
import Reusable

class MainViewController: UIViewController, BindableType {
    @IBOutlet weak var tableView: UITableView!
    
    var viewModel: MainViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configView()
    }
    
    private func configView() {
        title = "Gitgub"
        tableView.do {
            $0.register(cellType: GithubRepoCell.self)
            $0.rowHeight = 80
        }
    }
    
    func bindViewModel() {
        let input = MainViewModel.Input(
            loadTrigger: Driver.just(()),
            selectTrigger: tableView.rx.itemSelected.asDriver()
        )
        let output = viewModel.transform(input)
        
        output.repos
            .drive(tableView.rx.items) { tableView, index, repo in
                let indexPath = IndexPath(item: index, section: 0)
                let cell: GithubRepoCell = tableView.dequeueReusableCell(for: indexPath)
                cell.setContentForCell(repo)
                return cell
            }
            .disposed(by: rx.disposeBag)
        
        output.selected
            .drive()
            .disposed(by: rx.disposeBag)
        
        output.indicator
            .drive(rx.isLoading)
            .disposed(by: rx.disposeBag)
        
        output.error
            .drive(rx.error)
            .disposed(by: rx.disposeBag)
    }
}

extension MainViewController: StoryboardSceneBased {
    static var sceneStoryboard = StoryBoards.main
}

3.2. ViewModel:

ViewModel sẽ đóng vai trò chuẩn bị và chung chuyển dữ liệu. Nó sẽ có ba thành phần chính gồm:
  • Input: tập các trigger đầu vào được tiếp nhận từ View.
  • Output: tập các giá trị đầu ra để thực hiện bind lên View.
  • func transform(input: Input) -> Output thực hiện biến đổi tập giá trị đầu vào thành kết quả đầu ra.
Ngoài ra, ViewModel còn chứa 2 thành phần là UseCase chịu trách nhiệm thực hiện các xử lý logic nghiệp vụ và Navigator chịu trách nhiệm điều hướng ứng dụng (chuyển màn hình, show alert,...).
Trong ví dụ, khi nhận được sự kiện kích hoạt load data từ loadTrigger thì sẽ thực hiện gọi API thông qua hàm getRepos() được định nghĩa trong UseCase. Hàm này sẽ trả về một Observable<[GithubRepo]>, bởi vậy nên nếu chúng ta muốn nhận được data trả về từ API response là [GithubRepo] thì phải sử dụng operator .flatMap { }. Sau đó sẽ chuyển kết quả vào Output để bind sang ViewController.
import Foundation
import RxSwift
import RxCocoa
import MGArchitecture

struct MainViewModel {
    let navigator: MainNavigatorType
    let useCase: MainUseCaseType
}

extension MainViewModel: ViewModelType {
    struct Input {
        let loadTrigger: Driver<Void>
        let selectTrigger: Driver<IndexPath>
    }
    
    struct Output {
        let repos: Driver<[GithubRepo]>
        let selected: Driver<Void>
        let error: Driver<Error>
        let indicator: Driver<Bool>
    }
    
    func transform(_ input: MainViewModel.Input) -> MainViewModel.Output {
        let indicator = ActivityIndicator()
        let error = ErrorTracker()
        
        let repos = input.loadTrigger
            .flatMapLatest { _ in
                return self.useCase.getRepos()
                    .trackActivity(indicator)
                    .trackError(error)
                    .asDriverOnErrorJustComplete()
            }
        
        let selected = input.selectTrigger
            .withLatestFrom(repos) { indexPath, repos in
                return repos[indexPath.row]
            }
            .do(onNext: { repo in
                self.navigator.toRepoDetail(githubRepo: repo)
            })
            .mapToVoid()
        
        return Output(
            repos: repos,
            selected: selected,
            error: error.asDriver(),
            indicator: indicator.asDriver()
        )
    }
}

3.3. UseCase:

Đóng vai trò xử lý các logic nghiệp vụ.
import Foundation
import RxSwift
import RxCocoa
import MGArchitecture
import MGAPIService

protocol MainUseCaseType {
    func getRepos() -> Observable<[GithubRepo]>
}

struct MainUseCase: MainUseCaseType {
    
    func getRepos() -> Observable<[GithubRepo]> {
        let request = GithubRepoRequest(page: 1)
        let repository = GithubRepoRepository()
        return repository.getGithubRepos(input: request)
    }
}

3.4. Navigator:

Đóng vai trò điều hướng ứng dụng.
import Foundation
import UIKit
import RxSwift
import RxCocoa

protocol MainNavigatorType {
    func toRepoDetail(githubRepo: GithubRepo)
}

struct MainNavigator: MainNavigatorType {
    unowned let navigationController: UINavigationController
    
    func toRepoDetail(githubRepo: GithubRepo) {
        let viewController = RepoDetailViewController.instantiate()
        let useCase = RepoDetailUseCase()
        let navigator = RepoDetailNavigator(navigationController: navigationController)
        let viewModel = RepoDetailViewModel(navigator: navigator,
                                            useCase: useCase,
                                            repo: githubRepo)
        viewController.bindViewModel(to: viewModel)
        navigationController.pushViewController(viewController, animated: true)
    }
}
Chúng ta có thể theo dõi luồng chạy thông qua Sequqence Diagram sau:

Source code demo: https://github.com/tgdong2296/SimpleDemoCleanArchitecture

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 - Codable (P1)

Codable được giới thiệu cùng với phiên bản 4.0 của Swift, đem lại sự thuận tiện cho người dùng mỗi khi cần encode/ decode giữa JSON và Swift object. Codable là alias của 2 protocols: Decodable & Encodable . Decodable: Chuyển data dạng string, bytes... sang instance (decoding/ deserialization) . Encodable: Chuyển instance sang string, bytes... (encoding/ serialization) Table of contents . Swift Codable basic . Swift Codable manual encode decode . Swift Codable coding key . Swift Codable key decoding strategy . Swift Codable date decoding strategy . Swift Codable nested unkeyed container Swift Codable basic Chúng ta sẽ đi vào ví dụ đầu tiên của Swift Codable, mục tiêu sẽ là convert đoạn JSON sau sang Swift object (struct) { "name": "NhatHM", "age": 29, "page": "https://magz.techover.io/" } Cách làm: Đối với JSON có dạng đơn giản thế này, công việc của chúng ta chỉ là define Swift struct to Codable proto...

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