Search code examples
iosswiftrx-swiftreactivemoya

Custom "flatmap" to call before each request


So what i have is an application that uses a REST endpoint, but before it can use it. It must call a register endpoint which assigns an DeviceId to the device which must be used in all subsequent API calls.

Currently I'm using Moya and RxSwift to chain and transform request.

What i was thinking that i would call a custom operator on my request like so

self.mapRect
         .waitForDeviceId()
         .flatMap { [weak self] mapRect -> Single<Response> in
                    ...
          weakSelf.provider.rx.request(PCDepartmentTarget.list(coordinate: center, distance: maxDistance))
          }
          .map(to: [PCParkingLot].self)
          .bind(to: self.parkingLotOVariable)
          .disposed(by: self.disposeBag)

Where i was thinking that waitForDeviceId() should look something like this.

extension ObservableType {

    func waitForDeviceId<R>() -> Observable<R> {

        PCDeviceIdService.shared.deviceIdObservable.flatMap { _ -> Observable<R> in
            return self
        }
    }
}

Which is clearly not compiling.

Do you have any ideas on how to implement such and operator or a perhaps a different way of doing it. Thank you in advance.


Solution

  • I think what you are trying to do should look like this:

    extension ObservableType {
    
        //E comes from ObservableType itself. You don't have to declare it.
        func waitForDeviceId() -> Observable<E> {
            //flatMap self catching the element (for example mapRect)
            return flatMap { e in
                PCDeviceIdService.shared.deviceIdObservable()
                    .map{ _ in e } //map deviceIdObservable back into e
            }
        }
    
    }