Home > Mobile >  .map and Foreach loop with RxSwift
.map and Foreach loop with RxSwift

Time:07-30

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<[CodingModel]>()

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 ?? ""])
}

CodePudding user response:

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.

CodePudding user response:

If I understand the question. Something like this should work:

func example(arrData: [Data]) {
    _ = Observable.from(arrData)
        .map { CodingModel(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

  • Related