swiftreactive-programmingrx-swiftfrprxalamofire

RXAlamofire not returning data ( error or not)


This is my non-reactive code that works just fine.

func getLatestHtml2 () {

Alamofire.request("https://www.everfest.com/fest300").responseString { response in
    print("\(response.result.isSuccess)")
    if let html = response.result.value {
        self.parseHTML(html: html)
    }
}

}

However when I make it reactive using this code.

  func getLatestHtml1() -> Observable<String> {

        return Observable<String>.create { (observer) -> Disposable in
            let request = Alamofire
                .request("https://www.everfest.com/fest300")
                .responseString { response in
                    print(response.result.value)
                    observer.onNext(response.result.value!)
                    observer.onCompleted()

            }
            return Disposables.create { request.cancel() }


        }
    }

I get no data in the print statement. I even used RxAlamofire, which I feel is the right way with this code and it has error checking:

func getLatestHtml() -> Observable<String?> {
        return RxAlamofire

            .requestData(.get,"https://web.archive.org/web/20170429080421/https://www.everfest.com/fest300" )
            .debug()
            .catchError { error in
                print(error)
                return Observable.never()
            }
            .map { (response, value) in
                print(response.statusCode)
                guard response.statusCode == 200 else { return nil }
                print(value)
                return String(data: value, encoding: String.Encoding.utf8)
            }
            .asObservable()



    }

which produced no data or errors anywhere. I need to know if my syntax is wrong or my thinking regarding reactive programming is wrong.

I cam calling it as .getLatestHTMLX(). Thanks !


Solution

  • Observable's are lazy, they don't do any work unless they are being watched (and will generally stop working as soon as nobody is watching.) This means you have to subscribe to an observable in order for it to start emitting values.

    Also, unless you explicitly share the observable, it will start a new request for every subscriber.