Please clarify Combine Demand usage

Combine has two related functions that support "demand", where Subscribers inform Publishers on the desired number of elements passed to them in a "receive" function. The below ignores infinite demand.


1)

func request(_ demand: Subscribers.Demand)

Subscriptions provide this function, and as the Apple Docs say:


"Tells a publisher that it may send more values to the subscriber."


Matt Gallagher supposes in his excellent 22 Combine Tests article that each of these demands should be additive, and when the Subscription sends elements to the Subscriber, it decrements the count.


2)

func receive(_ input: Self.Input) -> Subscribers.Demand


When a Subscriber receives data, it returns another demand, which the Apple docs state is:


"A Subscribers.Demand instance indicating how many more elements the subscriber expects to receive."


I have seen various interpretations on how these numbers relate, and I of course have my own that I'll postulate here.


---


A Publisher has a one element, and it gets a 'request(.max(10))' When it sends that to the Subscriber, and the return demand should be '.max(9)', a reminder to the Publisher (actually a Subscription created by the Publisher) that its expecting 9 more elements.


If for some reason the Subscriber decides to send in another request for .max(10), and the Publisher gets one more element, and messages the Subscriber with that one element, the return will then be .max(18), meaning, Subscriber wanted 10, then it wanted 10 more, but it has only received 2.


Alternate interpretations seem to be that the return from receive is additive to the running total. So any number other than 0 will increase what the Publisher can send.


Would be super if anyone in the know could help clarify!!!

Accepted Reply

OK, I better understand the context.


Did you ask the question to technical support ? Or on Swift.org ?

Replies

I did not try.


can't you test subscriber demand maxvalue, to know the number of pending demands ?

https://developer.apple.com/documentation/combine/subscribers/demand/3334826-max

Claude, I'm writing my own Publisher, Subscriber, and Subscriptions. Most everyone uses infinite demands so my questions don't apply, I really want to understand actual usage and with no demo code from Apple using it, no way to know.


I recently wrote a small article on Combine, and there are a slew of them on the web, and each has a different take on the topic. So many are wrong, and it would just be great to get this clarified.

OK, I better understand the context.


Did you ask the question to technical support ? Or on Swift.org ?

Combine is Apple proprietary, so I didn't think it appropriate (but did see another one there).

Done: forums.swift.org / t / need-help-using-combine-demand-back-pressure / 35015

I think this article can help you.

Processing Published Elements with Subscribers | Apple Developer Documentation