Rxswift + Moya + Realm

1.2k views Asked by At

Okay, so let's explain my goal first. I'm trying to build a structure to fetch items from Moya and map my items properly using realm Object in order to save them in the future. All that should be done using rxswift in order to get the reactivity associated.

Here are my 2 class:

import Foundation
import ObjectMapper
import RealmSwift

final class GroupContainer: Mappable {

    private(set) var items = List<Group>()

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        items <- (map["items"], transformation: RealmListTransform<Group>())

    }
}
import Foundation
import RealmSwift
import ObjectMapper

final class Group: Object, Mappable {

    private(set) dynamic var tag: String = ""
    private(set) dynamic var name: String = ""
    private(set) dynamic var groupLevel: Int = 0
    private(set) dynamic var groupPoints: Int = 0
    private(set) dynamic var members: Int = 0

    required convenience init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        tag <- map["tag"]
        name <- map["name"]
        clanLevel <- map["groupLevel"]
        clanPoints <- map["groupPoints"]
        members <- map["members"]
    }
}

And here is a sample struct to fetch and parse my data. Well this is the example provided by RxMoya. However in order to use ObjectMapper I can't the use mapObjectOptionnal method. I tried switching my model to ModelMapper instead but couldn't find a way to transform my array into an List I also tried to find a replacement to mapObjectOptionnal, for example mapArray, mapObject but for some reason i can't use them directly after making my request.

import Moya
import Moya_ObjectMapper
import RxOptional
import RxSwift

struct TempFetcher {
  let provider = RxMoyaProvider<APIService>()
  let groupName = Observable<String>

    func trackGroup() -> Observable<[Group]> {
        return self.groupName.observeOn(MainScheduler.instance)
                    .flatMapLatest { search -> Observable<GroupContainer> in
                            return self.findGroup(name: search)
                    }
                    .flatMapLatest { container -> Observable<[Group]> in
                            return Observable<[Group]>.just(container.items)
                    }
    }

    private func findGroup(name: String) -> Observable<GroupContainer?> {
        return self.provider
            .request(APIService.Group(fullName: name))
            .debug()
            .mapObjectOptional(type: Repository.self)
    }
}

Any help to progress in my research would be gladly appreciated!! Thanks.

1

There are 1 answers

0
Arnav On

I used these pods for implementing the same and the combination works for me .

pod 'Moya/RxSwift'
pod 'Moya-ObjectMapper/RxSwift'
pod 'ObjectMapper+Realm'

instead of mapObjectOptional use

  return Mapper<LoginResponse>().map(JSONObject: data)