1

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?

1 Answer 1

2

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
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I went with map since that more closely represents the intent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.