I'm newbie in Swift and Rx programming. Is my below code is declarative ? If not, please rewrite it and explain to help me more understanding about declarative :( (my English is so bad)

// MARK: RxSwift
func processPhotoApiService(target: PhotoService) -> Observable<[String: Any]> {
    return RxMoyaProvider<PhotoService>().request(target).map { try $0.mapJSON() as! [String: Any] }


ApiServiceManager.shared.processPhotoApiService(target: .getNews(consumerKey: ApiConstants.CONSUMER_KEY, page: 1, imageSize: ApiConstants.MEDIUM_IMG_SIZE))
    .map {
        NewsJson(json: $0)!.photos
    } .flatMap { photos in
        Observable.from(photos).flatMap { photo in
            Observable.from(optional: PhotoItem(name: photo.name, URL: photo.imageUrl, viewCount: photo.viewCount, ratingCount: photo.ratingCount))
    }.subscribe { event in
    switch event {
    case .next(let dictionary):
        print("onNext:", dictionary)
    case .error(let error):
        print("onOtherError:", error)
  • 2
    \$\begingroup\$ Welcome to Code Review! Please tell us what this code accomplishes, ideally with examples of inputs and outputs. See How to Ask. \$\endgroup\$ – 200_success Sep 10 '17 at 6:18
  • \$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$ – BCdotWEB Nov 13 '20 at 7:28

In order for code to be declarative, it must express an invariant. Something that is true throughout the entire life of the variables involved. In other words, a direct chain from input to output. Think Excel. In Excel, every cell in the spreadsheet is either an input variable or a transformation of one or more cells which recursively go back to input variables and that's what makes it declarative.

Your code is not declarative because it doesn't specify what user action would cause processPhotoApiService to get called.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.