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

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