07/09/2018, 17:07

RxSwift: Bài 6: RxCocoa (Part 2)

RxSwift: Bài 6: RxCocoa (Part 2) Retrieving data from the OpenWeather API Trong ApiController, ta thay fake data bằng đoạn code sau: func currentWeather(city: String) -> Observable<Weather> { return buildRequest(pathComponent: "weather", params: [("q", city)]) .map { json in ...

RxSwift: Bài 6: RxCocoa (Part 2)

Retrieving data from the OpenWeather API
Trong ApiController, ta thay fake data bằng đoạn code sau:

func currentWeather(city: String) -> Observable<Weather> {
  return buildRequest(pathComponent: "weather", params: [("q", city)])
  .map { json in
    return Weather(
      cityName: json["name"].string ?? "Unknown",
      temperature: json["main"]["temp"].int ?? -1000,
      humidity: json["main"]["humidity"].int  ?? 0,
      icon: iconNameToChar(icon: json["weather"][0]["icon"].string ??
"e")
) }
}

Trong này có hai function cần phân tích:

1.iconNameToChar: nó nhận 1 string từ data JSON và trả về 1 string khác dưới dạng UTF-8 code của icon thời tiết có hình dạng sẽ xuất hiện trên app của bạn:

public func iconNameToChar(icon: String) -> String {
    switch icon {
    case "01d":
        return "u{f11b}"
      //[...]
    default:
        return "E"
    }
}

2.convenience function buildRequest:
alt text
Nó dùng để tạo network requests, sử dụng RxCocoa’s wrapper đối với NSURLSession để perform như sau:

  • dùng URL rồi append GET (or POST) request
  • sử dụng API của mình để get data
  • đưa nội dung về dạng application/ json
  • chọn nhiệt độ (ở đây là Kevin)
  • đưa dạng json về model

Cuối cùng nó được kết thức bằng dòng sau:

 //[...]
return session.rx.data(request: request).map { JSON(data: $0) }

Cái này dùng rx extension của RxCocoa xung quanh NSURLSession cái mà sử dụng data function. Nó lần lượt trả về 1 Observable. Data này được dùng như là input data để map dùng chuyển từ raw data thành cấu trúc SwiftyJSON data.
Nhìn sơ đồ sau để hiểu rõ hơn cái gì bên trong ApiController:
alt text

Thay đoạn code Observable.just([...]) ban đầu bằng real data. Mở OpenWeatherMap API documentation http://openweathermap.org/current, nó sẽ giải thích kĩ cách lấy get/ post, ví dụ như sau:

api.openweathermap.org/data/2.5/weather?q={city name}

Cái request này sẽ trả về 1 JSON object, sau đó convert với những property cần thiết. Build and run và enter London, kết quả sẽ là:
alt text

App đã chạy rất ok, tuy nhiên nếu bạn refactor thì thử remove cái catchErrorJustReturn operator bên trong flatmap. Ngay khi nhận đc 404 error (thấy trong console ấy), app sẽ show Error như bt bởi vì mình đã xử lý nil coalescing bên trong rồi.
alt text

0