0

I am new to the combine world and have written a query that returns the results I need correctly. It's multi-step, but basically makes an api call over the network, parses the returned json and creates an array of records I need.

let results2: Publishers.Map<Publishers.ReceiveOn<Publishers.Decode<Publishers.Map<URLSession.DataTaskPublisher, JSONDecoder.Input>, Wrapper<Question>, JSONDecoder>, DispatchQueue>, [Question]>

I'm trying to rewrite a portion of my code and realize that I still don't quite grasp the ins and outs of parsing the results. If you look at the datatype of results2 you will see the final portion contains an array of Question. How do I assign this array to a variable, as in:

let finalAnswer: [Question] = turnThisIntoAnArray(results2)

If possible, I'd prefer a general answer to this general question, rather than providing all the code needed to recreate this specific string of publishers.

thanks

Mozahler
  • 4,958
  • 6
  • 36
  • 56
  • A Combine publisher doesn't return anything in terms of *return result*. You have to `sink` the pipeline and assign the `receivedValue` to `finalAnswer`. And assign `results2` to a strong reference of `AnyCancellable` type. – vadian Apr 05 '22 at 18:22
  • Thanks Vadian! I'm sure that you've answered my question correctly, but I haven't succeeded yet in turning your response into working code. I will continue to look into this. I appreciate your help. – Mozahler Apr 05 '22 at 19:27
  • @vadian If you want to write up an answer I'll accept it. Otherwise I'll close it tomorrow with a code example of how I got my array of objects. – Mozahler Apr 06 '22 at 15:33

1 Answers1

0

In this working example, notice the variable results below:

  func runQuery() {
     let env = BespokeEnvironment(mainQueue: .main, networkQuery: NetworkQuestionRequestor())
     results = env.networkQuery.reviewedQuestionsQuery(pageCount: 1)
        .sink(
           receiveCompletion: { print($0)},
           receiveValue: { values in
              returnValues.append(contentsOf: values)
           })
     }

I originally had:

 let results =
   ...

And was not getting any records. It turns out the method was completing and returning before the publisher had finished.

In the non-working code, the cancellable was not being saved long enough for the publisher to complete. So I moved results into the parent view and made it a @State variable. Everything now works correctly.

   @State var results: AnyCancellable? = nil
Mozahler
  • 4,958
  • 6
  • 36
  • 56