Home > Software engineering >  How to receive continuous stream of states from two publishers working together
How to receive continuous stream of states from two publishers working together

Time:09-27

I have a function getState(), the purpose of which is to return a continuous stream of States. I have two publishers: statePublisher and requestPipeline.

When I call getState(), the requestPipeline is sent a Request. As the pipeline progresses, it returns states to the statePublisher.

This statePublisher gets referenced strongly during the operator .doThingThree(statePublisher). This operator presents a View Controller which holds on to the statePublisher. When that view controller dismisses, it sends a State and then completes.

This is my current, broken, code:

func getState(request: Request) -> AnyPublisher<State, Never> {
  let statePublisher = PassthroughSubject<State, Never>()
  let requestPipeline = PassthroughSubject<Request, Error>()

  requestPublisher = requestPipeline
    .eraseToAnyPublisher()
    .doThingOne()
    .doThingTwo(statePublisher)
    .doThingThree(statePublisher)


  requestPipeline.send(request)


  return statePublisher
    .eraseToAnyPublisher()
}

func getMyState() {
  cancellable = getState(request: myRequest)
    .sink { state in
      print(state) // Never gets fired
    }
}

Unfortunately calling getMyState() doesn't do anything. Do I need to subscribe to the requestPublisher before I can do anything? Any help appreciated!

CodePudding user response:

You do have to subscribe to a PassthroughSubject before you send any values through it in order to receive events.

In your code you call getState.

getState calls send.

The send is ignored because there are no subscribers to requestPipeline.

Then getState returns.

You then you subscribe to statePublisher with sink.

Your code doesn't show any values ever being sent to statePublisher.

If there are were events being sent in doThingTwo and doThingThree then they are sent long before sink subscribes to statePublisher.

But then again doThingTwo and doThingThree are never invoked in the code that you've shown because there are no subscribers to requestPublisher or requestPipeline

If you are unsure if your publishers are executing use the .print(<name>) operator to see subscriptions and values passing through the pipeline.

  • Related