jbreckmckye / trkl

Reactive microlibrary with observables and spreadsheet-style computed values in 383 bytes
Apache License 2.0
187 stars 5 forks source link

Is there a reason subscribe callbacks are called in reverse order? #6

Closed micahjon closed 3 years ago

micahjon commented 3 years ago

I noticed that the most recent subscribe() callback is fired first when the value changes. This is a bit counter-intuitive compared to events in the browser and other subscription models I've used, which are first-in, first-out.

Could you explain why this decision decision was made? Just trying to wrap my head around things. Thanks again!

jbreckmckye commented 3 years ago

HI @micahjon

This was an easy way to ensure a callback could safely remove itself from the list.

Imagine having a set of four callbacks. In interation 2, you call callback 3 (zero-indexed), but it removes itself from the list. Next iteration you are on n=3, which should point to the fourth item, but there are only 3 items in the list.

Whereas, if you process the array in reverse, this is largely a non-issue.

micahjon commented 3 years ago

Thanks @jbreckmckye , I see what you mean.

I suppose the only way of getting around this would be cloning the array before iterating. Feels like it might be worth it to keep the iteration order predictable, but I understand that keeping things super minimalist is important to you.

jbreckmckye commented 3 years ago

That is actually how it used to work; I got rid of it to a) save space and b) eliminate a heap allocation.

As an aside, is there a context where you'd find a FIFO style iteration particularly useful?