ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • RxSwift - API Call
    Swift/RxSwift 2022. 7. 26. 15:31

     

    func fetchEvents(repo: String) {
        let response = Observable.from([repo])
          .map { urlString -> URL in
            return URL(string: "https://api.github.com/repos/\(urlString)/events")!
          }
          .map { url -> URLRequest in
            return URLRequest(url: url)
          }
          .flatMap { request -> Observable<(response: HTTPURLResponse, data: Data)> in
            return URLSession.shared.rx.response(request: request) // this method returns 'Observable'
            // completes whevever your app receive the full response form the web server.
          }
          .share(replay: 1) //  Finally, to allow more subscriptions to the result of the web request, chain one last operator. You will use share(replay:, scope:) to share the observable and keep in a buffer the last emitted event:
        response
          .filter { response, _ in
            return 200 ..< 300 ~= response.statusCode
          }
          .compactMap { _, data -> [Event]? in // lets through any non-nil values ( filters any nils )
                                              // discard the response object and take only the response data
            return try? JSONDecoder().decode([Event].self, from: data) // attempt to decode the response data as an array of Events.
                                                                      // use a try? to return a nil value in case the decoder throws an error while decoding the JSON data.
          }
          .subscribe(onNext: { [weak self] newEvents in
            self?.processEvents(newEvents)
          })
          .disposed(by: bag)

     

    // flatMap -> return  Observable<(response: HTTPURLResponse, data: Data)>
    // map -> return Observable<Observable<(response: HTTPURLResponse, data: Data)>>

     

    'Swift > RxSwift' 카테고리의 다른 글

    Login Validation (simple..) RxSwift 구현  (0) 2022.09.29
    RxSwift basic test (count 1씩 올리기)  (0) 2022.09.28
    RxSwift Merge 이용해서 Event 묶기  (0) 2022.07.20
    Difference between bindTo and drive ( RxSwift)  (0) 2022.03.30
    Observables  (0) 2022.03.25
Designed by Tistory.