skip to Main Content

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


  1. try to use flatMap instead of last map – u need to unwrap the publisher and execute it, instead, u just create a publisher that consist from 2 task

    also, are u sure about

    .receive(on: RunLoop.main)
    

    read more about RunLoop.main scheduler here

    Login or Signup to reply.
  2. I think what you really want to do is this:

    _ = userService.getToken()
            .receive(on: DispatchQueue.main)
            .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)
            })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search