onmyway133 / notes

:notebook_with_decorative_cover: Issues and solutions I found during development, mostly iOS
https://onmyway133.com/
MIT License
62 stars 4 forks source link

RxSwift if else inside flatMap not work #93

Open onmyway133 opened 8 years ago

onmyway133 commented 8 years ago
func authorize(user: User) -> Observable<(Client, Authorization)> {
      return Observable<(Client, Authorization)>.deferred {
        let client = Client(unauthenticatedUser: user)

        let observable = client.enqueue(requestDescriptor).map {
          return Parser.one($0.jsonArray) as Authorization
        }

        return Observable.combineLatest(Observable<Client>.just(client), observable) {
          return ($0, $1)
        }
      }
    }

    return
      authorize(user)
      .flatMap { (client: Client, authorization: Authorization) in

        if authorization.token.isEmpty {
          var requestDescriptor = requestDescriptor
          requestDescriptor.then {
            $0.path = "authorizations/\(authorization.objectID)"
            $0.method = .DELETE

            if let oneTimePassword = oneTimePassword {
              $0.headers[Client.Constant.oneTimePasswordHeaderField] = oneTimePassword
            }
          }

          return client.enqueue(requestDescriptor).flatMap { _ in
            return authorize(user)
          }
        } else {
          return Observable<(Client, Authorization)>.just((client, authorization))
        }
      }
      .catchError { error in
        let error = error as NSError

        return Observable<(Client, Authorization)>.error(error)
      }
      .map { (client: Client, authorization: Authorization) in
        client.token = authorization.token

        return client
      }
onmyway133 commented 8 years ago

Need to make stuff inside flatMap a function that returns wanted value