Search code examples
iosswiftcombine

Swift Combine chain 2 network request synced


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?


Solution

  • So the missing part was adding: private var cancellables = Set<AnyCancellable>() and then add this to the end of the chain .store(in: &cancellables)

     _ = userService.getToken()
            .flatMap { self.userService.getBand(token: $0.access_token) }
            .sink(receiveCompletion: { [weak self] _ in
                self?.loading = false
            },receiveValue: { [weak self] result in
                self?.loading = false
                print(result)
            }).store(in: &cancellables)