so i am kinda new to Combine and i am trying to do 2 network requests one after another.
func fetchData2() {
loading = true
print("👻 fetchData")
_ = userService.getToken()
.receive(on: RunLoop.main)
.map { $0 }
.compactMap { self.userService.getBand(token: $0.access_token) }
.map { $0 }
.sink(receiveCompletion: { [weak self] _ in
self?.loading = false
},receiveValue: { [weak self] result in
self?.loading = false
print(result)
})
}
protocol UserServiceProtocol {
func getToken() -> AnyPublisher<TokenModel, Error>
func getBand(token: String) -> AnyPublisher<BandModel, Error>
}
These are the models:
struct TokenModel: Codable {
var access_token: String
var token_type: String
var expires_in: Int
}
struct BandModel: Codable {
var external_urls: External
var followers: Follower
var genres: [String]
var href: String
var id: String
var images: [ImageCode]
var name: String
var popularity: Int
var type: String
var uri: String
}
The result gives me : <PublisherBox<Decode<TryMap<SubscribeOn<DataTaskPublisher, OS_dispatch_queue>, Data>, BandModel, JSONDecoder>>: 0x600002911ce0>
and i am expecting BandModel.
what am i missing?
2
Answers
try to use
flatMap
instead of lastmap
– u need to unwrap thepublisher
and execute it, instead, u just create apublisher
that consist from 2 taskalso, are u sure about
read more about
RunLoop.main scheduler
hereI think what you really want to do is this: