There are many ways to generate data and use it in programming. Infinite ways. I just want to talk about two. The two ways that i am in love with. To choose which one to implement is depended on your requirements. I will try to explain when to use them and their key differences in this article.

Supply on demand

  • Function/Supplier is passive.
  • Caller/Consumer is active.

This is the most common data supply way in programming. In this design, data being supplied by the supplier when the observer make demand for it. To implement this method is very simple. It can be built by just a method and a pair of controlled loops. A function gets called when caller is ready to handle the generated value, then function generates the data and returns it to the caller. Or it can be a little different by using Supplier/Consumer pair, a consumer callback method being passed to a supplier and then supplier calls the consumer with a parameter that contains the generated data after the data is ready. But the thing is, both of these alternatives generate data on the demand. Caller/Consumer determines when to get the data.

Example implementations,

  • Supplier/Function interfaces in Java
  • HTTP API implementations
  • Generators/Iterators in many languages

Of course there are many sub types of this design. You need to choose one of them by your requirements. Let me list a few,

  • If the data is finite, there must be common control mechanism which terminates the loop when it is end of the supply. A “null” return as an example. Of course it is not applicable always, some times supplied data can be null. A common way is to box the returned value with a control flag.
  • If supplier function calls another supplier inside its logic, it’s better to pass a callback function as a handler for consuming the iterating value. Supplier passes the consumer callback to the dependent suppliers.
  • If your implementation needs a loop which needs to be able to get paused and resume later, you may need to use another variable which contains next step on the data generation. And every supplier must pass this variable to the other recursive suppliers.

Some important things about this design,

  • Do not make the caller waiting for generation of the asynchronous data. If the data is not ready, just inform the caller about it. Also, it is already a bad idea to use this design with asynchronous data generation because of its nature. See the next chapter if you have to implement asynchronous one.

#observables #reactive-programming #observer #suppliers #consumer #function

Reactive and Functional Programming Design Patterns
1.10 GEEK