Hey, beanskins. Hello again.
As we all know, RxJS is a very popular front-end responsive asynchronous programming framework, and its rich operators bring infinite possibilities for asynchronous programming. However, the students of data platform “Yang Xie” have encountered the problem of reverse flow of observation values. The following article describes the cause and solution process of the problem.
The author: Yang Xian
The introduction
RXJS has always been the best solution to complex asynchronous problems by flowing values like magic from Observable to Observable, but recently I ran into a problem where values can flow in the opposite direction, as with TENET, which is very counterintuitive.
The problem code
To locate the problem, I wrote a minimal replay demo. The following code subscribes to a Subject and prints the current value. The question is, what is the print result?
Codesandbox. IO/s/lucid – alm…
The printed result is:
-
1
-
2
-
3
Is that true?
But the actual result is:
-
3
-
2
-
1
Oh, my God, how is that possible? Did I go through TENET? Why is the output inverted?
In-depth analysis
To further explore this question, let’s write a minimum Subject together
One thing to note during the implementation process:
RXJS is a complex asynchronous solution, but it is synchronous in nature
Also in the problem code, the first subscribe plus the log that starts with sub1, the second subscribe plus the log that starts with sub2
The results are as follows
-
sub1 1
-
sub1 2
-
sub1 3
-
sub2 3
-
sub2 2
-
sub2 1
Further simplifying, we end up with a simple recursive model:
Let me draw a stack diagram
So that’s pretty neat
The solution
Going back to the original problem, what are the solutions if we want the values in our App to be printed sequentially?
The idea is to use microtasks to create a new task without using the current stack
Method one:
Using setTimeout
Method 2:
Using delayoperator
Or something like that
conclusion
Don’t panic when you encounter a problem, minimize the complexity of the problem, and finally find that it is a simple problem, and the solution to the smallest simple problem is usually the solution to the final complex problem.
The End
Reference: Rxjs TENET resolution