Skip to main content

Tạo màn hình Login sử dụng RXSwift + MVVM


Chào mọi người, trong bài viết lần này mình sẽ chia sẻ cách áp dụng rxswift vào một project nhỏ dùng để validate các textfield mà người dùng nhập vào kết hợp với mô hình MVVM.

MVVM

Mô hình MVVM thì chắc các bạn dev đều đã biết đến. Ưu điểm của MVVM là gì? Mình có đọc được bài viết của một anh rất hay nên có dẫn link ngay trong bài này: Swift: Những lợi ích của MVVM (Model - View - ViewModel)

Bắt đầu với RxSwift

Đây là hình ảnh phần demo nhỏ Thoả mãn điều kiện Thoả mãn điều kiện Không thoả mãn điều kiện Không thoả mãn điều kiện
Đầu tiên, chúng ta sẽ tạo một project. Ở đây mình đặt tên project là "RxExample1". Tiếp theo mình sẽ pod thư viện RxSwift về project. Sau khi pod install thành công, mở thư mục chứa project và mở file "RxExample1.xcworkspace". Đầu tiên, chúng ta sẽ cần tạo UI cơ bản. Ở đây mình tạo UI chỉ đơn giản với 2 textfield cho việc nhập thông tin bao gồm: email và password. Tiếp theo là 2 label dành cho việc hiển thị messsage error đối với mỗi textfield. Cuối cùng là một button cho việc handle login. UI Layout

MVVM

Ở đây mình sẽ sử dụng mô hình MVVM để tạo ra class LoginViewModel sử dụng cho việc sử lý logic và mapping dữ liệu với Model.
    import RxSwift
    
    class LoginViewModel {
        
        // Khai báo biến để hứng dữ liệu từ VC
        var usernameText = Variable<String>("")
        var passwordText = Variable<String>("")
        
        
        // Khai báo viến Bool để lắng nghe sự kiện và trả về kết quả thoả mãn điều kiện
        var isValidUsername: Observable<Bool> {
            return self.usernameText.asObservable().map { username in
                username.count >= 6
            }
        }
        
        var isValidPassword: Observable<Bool> {
            return self.passwordText.asObservable().map {
                password in
                password.count >= 6
            }
        }
        
        // Khai báo biến để lắng nghe kết quả của cả 2 sự kiện trên
        
        var isValid: Observable<Bool> {
            return Observable.combineLatest(isValidUsername, isValidPassword) {$0 && $1}
        }
    }

Ở trong LoginViewModel, mình có sử dụng toán tử combineLatest. Vậy nó có nghĩa là gì? combineLatest là một toán tử mà dùng để chúng ta lấy ra một kết quả mà cần dựa vào sự kết hợp của các Observable khác nhau. Trong ví dụ trên thì mình sử dụng nó để tạo ra biến isValid, biến isValid sẽ trả về kết quả dựa theo 2 observable là isValidUsername và isValidPassword. -> { $0 && $1 } là gì? Nó được gọi là resultSelector, ở đây nó đã được rút gọn tương ứng với value của input observable. (isValidUsername, isValidPassword) {$0 && $1}
--
Tiếp theo là chúng ta sẽ xử lý trong ViewController
import UIKit
import RxSwift
import RxCocoa

class LoginViewController: UIViewController {
    
    @IBOutlet fileprivate weak var tfAccount: UITextField!
    @IBOutlet fileprivate weak var tfPassword: UITextField!
    @IBOutlet fileprivate weak var lbErrorEmail: UILabel!
    @IBOutlet fileprivate weak var lbErrorPassword: UILabel!
    @IBOutlet fileprivate weak var btnLogin: UIButton!
    
    var viewModel: LoginViewModel!
    let disposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        // set delegate
        tfAccount.delegate = self
        tfPassword.delegate = self
        //init viewmodel
        viewModel = LoginViewModel()
        
        //bind value of textfield to variable of viewmodel
        _ = tfAccount.rx.text.map { $0 ?? "" }.bind(to: viewModel.usernameText)
        _ = tfPassword.rx.text.map { $0 ?? "" }.bind(to: viewModel.passwordText)
        
        //  subscribe result of variable isValid in LoginViewModel then handle button login is enable or not?
        _ = viewModel.isValid.subscribe({ [weak self] isValid in
            guard let strongSelf = self, let isValid = isValid.element else { return }
            strongSelf.btnLogin.isEnabled = isValid
            strongSelf.btnLogin.backgroundColor = isValid ? UIColor.red : UIColor.gray
        })
    }
    
    @IBAction func actionLogin(_ sender: Any) {
        //do something
    }
    
}

extension LoginViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case self.tfAccount:
            self.viewModel.isValidUsername.subscribe({ [weak self] isValid in
                self?.lbErrorEmail.text = isValid.element! ? "Valid username" : "Invalid username"
            }).disposed(by: disposeBag)
        case self.tfPassword:
            viewModel.isValidPassword.subscribe({ [weak self] isValid in
                self?.lbErrorPassword.text = isValid.element! ? "Valid password" : "Invalid password"
            }).disposed(by: disposeBag)
        default:
            return
        }
    }
}
Tiếp theo run project và test thử.
Xin cảm ơn mọi người đã đọc đến đây
Github repo:https://github.com/dungkv95/RxExample1

Comments

Popular posts from this blog

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

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