Search code examples
rx-swift

Different types RxSwift


I don't know how to map custom types. I have two variables with custom types -

var viewModel: PurchaseList.Fetch.ViewModel? var response: PurchaseList.Fetch.Response?

    struct Response: Mappable {
        var shoppingList : [ShoppingList]?
    }

    struct ShoppingList: Mappable {
    var name: String?
    var offers: [Offers]?
    }

    struct Offers {
    var fullPrice: String?
    }

and

struct ViewModel {
var name: String?
var offers: [ViewModelOffers]?
}

struct ViewModelOffers {
var fullPrice: String?
}

how I can create var viewModel: PurchaseList.Fetch.ViewModel? from var response: PurchaseList.Fetch.Response? using RxSwift?


Solution

  • Based on the types you presented, I'm guessing that you are looking for code something like the below. This code has a lot of accidental complexity because of the excessive use of Optionals (the ?) in the types.

    There is virtually no reason for Strings or Arrays to be optional. Logically, an empty string is no different than a nil string (and an empty array is no different than a nil array) in 99.99% of cases. As such, a strong argument would need to be presented to justify making them optional.

    func example(_ from: Observable<Response?>) -> Observable<[ViewModel]?> {
        return from
            .map { $0?.shoppingList ?? [] }
            .map { $0.map{ $0.map(ViewModel.init) } }
    }
    
    extension ViewModel {
        init(_ shoppingList: ShoppingList) {
            name = shoppingList.name
            offers = shoppingList.offers?.map { ViewModelOffers(fullPrice: $0.fullPrice) }
        }
    }