Skip to main content

Dùng thư viện RXSWIFT để cải tiến hiệu suất cho dự án iOS của bạn — phần 4

Phần tiếp theo chúng ta sẽ tìm hiểu các operator còn lại
4.Create Operator
  • Create : khởi tao 1 obervable, trả về các observer dùng onNext,onComplete,OnError.

func createGoogleDataObservable() -> Observable<String> {
        
        return Observable<String>.create({ (observer) -> Disposable in
            
            let session = URLSession.shared
            let task = session.dataTask(with: URL(string:"https://www.simple.com")!) { (data, response, error) in
                
                DispatchQueue.main.async {
                    if let err = error {
                            observer.onError(err)
                    } else {
                        if let string = String(data: data!, encoding: .ascii) {
                            observer.onNext(string!)
                        } else {
                            observer.onNext("Error! Parse!")
                        }
                        observer.onCompleted()
                    }
                }
            }
            
            task.resume()            return Disposables.create(with: {
                task.cancel()
            })
        })
}
  • From : chuyển các objects và data type thành array observable

let observalbe : Observable<Int> = Observable.from([1,2,3,4,5])
observalbe.subscribe(onNext: {
        print($0)
})
.disposed(by: disposeBag)
  • Just : tạo ra chỉ một observable

let observable = Observable<String>.just("Init string")
observalbe.subscribe(onNext: {
        print($0)
    })
.disposed(by: disposeBag)
  • Of : tạo ra 1 array hoặc 1 observable
// Tạo ra 1 single 
let observalbe = Observable.of([1,2,3,4,5]) //[1,2,3,4,5]// Tạo ra 1 array
let observalbe = Observable.of(1,2,3,4,5)//1
//2
//3
//4
//5
5.Error Handling : trong ứng dụng chúng ta sẽ thường xuyên có nhiều error như : no internet connection , error input , API error, parse error… Chúng ta cần bắt error trong observable.
+Catch : dùng để bắt lỗi từ onError và sẽ tiếp tục sequence

Catch
Cách gồm : catchError vs catchErrorJustReturn
  • catchError : khi onError return về block kèm theo tham số NSError
public func catchError(_ handler: @escaping (Error) throws -> RxSwift.Observable<Self.E>) -> RxSwift.Observable<Self.E>
Ví dụ: Trả về tiếp 1 observable có giá trị mặc định

.catchError { error in
  if let text = text, let cachedData = self.cache[text] {
    return Observable.just(cachedData)
  } else {
    return Observable.just(Model())
  }
}
  • catchErrorJustReturn : set giá trị khi error
public func catchErrorJustReturn(_ element: Self.E) -> RxSwift.Observable<Self.E>
Ví dụ : Trả về mảng rỗng
let searchResults = searchText
.throttle(0.3, $.mainScheduler)
.distinctUntilChanged
.flatMapLatest { query in
      API.getSearchResults(query)
      .retry(3)
      .startWith([])
      .catchErrorJustReturn([])
}
+Retry : thử lại khi lỗi, và thường đặt trước khi cach error

Retry
Ví dụ : retry 3 lần
.retry(3)
.catchError { error in
  if let text = text, let cachedData = self.cache[text] {
    return Observable.just(cachedData)
  } else {
    return Observable.just(Model())
  }
}
Dùng retryWhen để check nâng cao
.retryWhen { e in
  return e.flatMapWithIndex { (error, numberTry) -> Observable<Int> in
    if numberTry >= maxRetry - 1 {
      return Observable.error(error)
    }
    return Observable<Int>.timer(Double(numberTry + 1), scheduler: MainScheduler.instance).take(1)
 } 
}
  • Custom error : dùng enum để define.Dùng throw hoặc Observable.error
enum ApiError: Error {
  case noInternetConnection
  case serverError
}return session.rx.response(request: request).map() { response, data in
  if 200 ..< 300 ~= response.statusCode {
    return JSON(data: data)
  } else if 400 ..< 500 ~= response.statusCode {
    throw ApiError.cityNotFound 
    //return Observable.error(ApiError.cityNotFound)} else {
    throw ApiError.serverError
    //return Observable.error(ApiError.serverError)
  }
}//Check error
onError: { [weak self] e in

}
6.Các Utility thường dùng
  • observeOn : chuyển thread(queue) khi obserser nhận đc notification
Ví dụ : Update UI ở main thread
observable
    .observeOn(MainScheduler.instance)
    .subscribe(onNext: { (data) in]
        //Update UI on Main Thread
    })
.addDisposableTo(disposeBag)
  • subcribeOn : chuyển thread(queue) khi bắt đầu xử lý observable
Ví dụ : xử lý ở background thread trc khi trả về
// Scheduler
let bgScheduler = ConcurrentDispatchQueueScheduler(qos: .background)sequence
  .subcribeOn(bgScheduler)
  .map { n in
      print("This is performed on the background scheduler")
  }
  .observeOn(MainScheduler.instance)
  .map { n in
      print("This is performed on the main scheduler")
  }
7. Schedulers : 1 loại giống như thread/queue , chúng ta muốn thread chạy trong subcribeOn or observeOn thực hiện :
  • MainScheduler : main thread.
Ví dụ :
// Background concurrent Scheduler
let bgScheduler = ConcurrentDispatchQueueScheduler(qos: .background)// Default concurrent Scheduler
var myWorkScheduler: SchedulerType = ConcurrentDispatchQueueScheduler(qos: .default)// Main Scheduler 
MainScheduler.instance// BG OperationQueueScheduler
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount  = 3
operationQueue.qualityOfService = .background
let bgScheduler = OperationQueueScheduler(operationQueue: operationQueue)
Phần sau mình sẽ giới thiệu các bạn về RxCocoaBinding.

Comments

Popular posts from this blog

MVVM và VIPER: Con đường trở thành Senior

Trong bài viết trước chúng ta đã tìm hiểu về MVC và MVP để ứng dụng cho một iOS App đơn giản. Bài này chúng ta sẽ tiếp tục ứng dụng 2 mô hình MVVM và VIPER . Nhắc lại là ứng dụng của chúng ta cụ thể khi chạy sẽ như sau: Source code đầy đủ cho tất cả mô hình MVC, MVP, MVVM và VIPER các bạn có thể download tại đây . MVVM MVVM có thể nói là mô hình kiến trúc được rất nhiều các cư dân trong cộng đồng ưa chuộng. Điểm tinh hoa của kiến trúc này là ở ViewModel , mặc dù rất giống với Presenter trong MVP tuy nhiên có 2 điều làm nên tên tuổi của kiến trúc này đó là: ViewModel không hề biết gì về View , một ViewModel có thể được sử dụng cho nhiều View (one-to-many). ViewModel sử dụng Observer design pattern để liên lạc với View (thường được gọi là binding data , có thể là 1 chiều hoặc 2 chiều tùy nhu cầu ứng dụng). Chính đặc điểm này MVVM thường được phối hợp với các thư viện hỗ trợ Reactive Programming hay Event/Data Stream , đây là triết lý lập trình hiện đại và hiệu

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 can be found within the s

Fileprivate vs private: Giải thích sự khác biệt

Fileprivate vs private in Swift: The differences explained Fileprivate and private are part of the access control modifiers in Swift. These keywords, together with internal, public, and open, make it possible to restrict access to parts of your code from code in other source files and modules. The private access level is the lowest and most restrictive level whereas open access is the highest and least restrictive. The documentation of Swift will explain all access levels in detail to you, but in this blog post, I’m going to explain the differences between two close friends: fileprivate and private. 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! Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level. This will improve readability and mak