iOS 14迁移时Combine框架flatMap歧义调用问题求助
解决iOS 14迁移中Combine flatMap的歧义错误
这个错误是因为iOS 14的Combine框架给flatMap新增了带maxPublishers参数的重载方法,编译器没法自动判断你要调用的是旧的无并发限制版本,还是新的带并发数限制版本,所以抛出了歧义提示。
解决方法
直接在flatMap里显式指定maxPublishers参数,明确告诉编译器使用哪个重载即可,一般用.unlimited保持和iOS 13时的行为一致。另外注意你代码里的一个小问题:第二个flatMap里的id变量未定义,应该改成$0.id。
修正后的完整代码
func fetchOptions( forLatitude latitude: Double, andLongitude longitude: Double, ofTypes types: [Option.Type], completion: @escaping (Result<[Option], Error>) -> Void ) { var cancellables: Set<AnyCancellable> = [] Deferred { Future { handler in self.someFetcher.fetchServices( byLatitude: latitude, andLongitude: longitude, completion: handler ) } }.eraseToAnyPublisher() // 第一个flatMap添加maxPublishers参数 .flatMap(maxPublishers: .unlimited) { Publishers.Sequence(sequence: $0).eraseToAnyPublisher() } .filter { types.map { $0.id}.contains($0.id) } // 第二个flatMap添加maxPublishers参数,同时修正id为$0.id .flatMap(maxPublishers: .unlimited) { service in Publishers.Zip( Just(service).setFailureType(to: Error.self), Deferred { Future { handler in self.fetcher.fetch(forId: service.id, completion: handler) } }.eraseToAnyPublisher() ).eraseToAnyPublisher() } .compactMap(mapToOption) .collect() .map { Array(Set($0)) } .sink { complete in switch complete { case .failure(let error): completion(.failure(error)) case .finished: return } cancellables.forEach { $0.cancel() } } receiveValue: { options in completion(.success(options)) } .store(in: &cancellables) }
补充说明
如果需要限制并发请求数,把.unlimited换成具体的数值(比如.max(5))即可,这样能避免同时发起过多请求导致的性能问题,这也是iOS 14新增这个重载的目的。
内容的提问来源于stack exchange,提问作者michael-martinez
相关产品推荐
相关产品推荐

