Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2609

Using RxAlamofire to create Observable contain the result of network request

I'm trying to work with RxAlamofire to wrap a network request result.

My objective is to fire request, handle JSON response and create and Observable that contain either network operation success or any error occur.

In other place I can call the function that create the Observable and subscribe to it and notify user whether it is success or failure with error message.

My implementation is below:

func discoverMovieList(for url: String, withPagg page: Int) -> Observable<Any> {
        let requestUrl = "\(url)&page=\(page)"

        return RxAlamofire.json(.get, requestUrl)
            .map{ jsonResponse in
                    self.createOrUpdateMoviesList(from: JSON(jsonResponse))
                }
    }

How can we correct the code and how we call it from other place to notify the result of the process?

Upvotes: 2

Views: 1548

Answers (1)

tomahh
tomahh

Reputation: 13651

Observable define multiple lifecycle callback, that you provide using the subscribe method. In this instance, usage would be something like this:

discoverMovieList(for: "http://some.url", withPagg: 2)
  .subscribe(
    onNext: { movies in
      uiElement.string = "Movie list received"
    },
    onError: { error in
      uiElement.string = "Something went wrong"
    }
  )
  .disposed(by: disposeBag)

disposeBag is used to hold the subscription, so when disposeBag is released, the subscription is cancelled (in our case, the network call would be aborted).

Upvotes: 0

Related Questions