David James David James - 2 months ago 20
Swift Question

RxSwift toArray does not compile with generic parameter

RxSwift

toArray
is not working for me when using generics:

struct SaveModelsCommand<M> where M:Model {

let models:[M]

func create() -> Observable<[M]> {

let cloudKitRecords:[CKRecord] = models.map({
// convert models to CKRecords
...
})

return SaveRecordsCommand(cloudKitRecords)
.createObservable()
.flatMap({ savedRecords in
// convert array to multiple emissions so we can iterate it
return Observable.from(savedRecords)
})
.flatMap({ (record:CKRecord) -> M in
// convert CKRecord back to a model (aka M)
... create model (e.g. Member) ...
return model
})
// convert back to a single emission (array)
.toArray() // <<<<< ERROR
}
}


Here is the error:


Cannot convert return expression of type 'Observable<[M.E]>' (aka 'Observable>') to return type 'Observable<[M]>' (aka 'Observable>')


The only difference that I can see in the return type is
M.E
vs
M
.

Any ideas?

Answer

flatMap expects the closure to return an Observable<M>, not just a plain M:

.flatMap({ (record:CKRecord) -> Observable<M> in
    // convert CKRecord back to a model (aka M)
    //... create model (e.g. Member) ...
    return Observable.just(model)
})

Alternatively, you can use map and just return an M:

.map({ (record:CKRecord) -> M in
    // convert CKRecord back to a model (aka M)
    //... create model (e.g. Member) ...
    return model
})
Comments