skip to Main Content

I have a csv file and I am storing into Sqlite.db. All is perfectly running in swift. Now I am going to convert .map and forEach to rxSwift.

Everytime I am getting an error cannot assign value of type [CodigoModel] to publishSubject.

I am new to RxSwift not getting an idea.

this is my code:

var arrCodigo = PublishSubject<[CodigoModel]>()

self.arrCodigo = arrData.map({ (data) -> CodigoModel in
return CodigoModel.init(data: data)
})
self.arrCodigo.forEach { (obj) in
                        
// store in sqlite db
_ = DBManager.shared.insert(tableName: "codigo_list", dataInDic: [
    "cod_distrito": obj.cod_distrito ?? "",
    "cod_concelho": obj.cod_concelho ?? "",
    "cod_localidade": obj.cod_localidade ?? "",
    "nome_localidade": obj.nome_localidade ?? "",
    "desig_postal": obj.desig_postal ?? ""])
}

2

Answers


  1. Not familiar with RxSwift, but if it is similar to Combine, you are assigning [CodigoModel] to a publisher.

    In Combine it would look something like this.

    var codigoPublisher = PassThroughSubject<[CodingModel]>()
    
    self.arrCodigo = arrData.map({ (data) -> CodigoModel in
    return CodigoModel.init(data: data)
    })
    
    codigoPublisher.send(self.arrCodigo)
    

    you would need to setup a subscriber to receive that value.

    Login or Signup to reply.
  2. If I understand the question. Something like this should work:

    func example(arrData: [Data]) {
        _ = Observable.from(arrData)
            .map { CodigoModel(data: $0) }
        // assuming you don't want the below on the main thread
            .observe(on: SerialDispatchQueueScheduler(qos: .background))
            .subscribe(onNext: { obj in
                _ = DBManager.shared.insert(tableName: "codigo_list", dataInDic: [
                    "cod_distrito": obj.cod_distrito ?? "",
                    "cod_concelho": obj.cod_concelho ?? "",
                    "cod_localidade": obj.cod_localidade ?? "",
                    "nome_localidade": obj.nome_localidade ?? "",
                    "desig_postal": obj.desig_postal ?? ""])
            })
    }
    

    No need for a subject here. And since you are learning Rx, remember this quote:

    Subjects provide a convenient way to poke around Rx, however they are not recommended for day to day use… Instead of using subjects, favor the factory methods…
    — Introduction to Rx

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search