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