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

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

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

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