Created
June 12, 2018 13:09
-
-
Save panteamihai/2aabaf7a441c6a69905e04b39e7b3243 to your computer and use it in GitHub Desktop.
Lazy evaluation in action with generators, and eager evaluation with lists (from Intro to RX)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void HotIsEager_ColdIsLazy_InTheEnumerableObservableDuality() | |
{ | |
void ReadFirstValue(IEnumerable<int> list) | |
{ | |
foreach (var i in list) | |
{ | |
Console.WriteLine("Read out first value of {0}", i); | |
break; | |
} | |
} | |
IEnumerable<int> EagerEvaluation() | |
{ | |
var result = new List<int>(); | |
Console.WriteLine("About to return 1 eagerly"); | |
result.Add(1); | |
//The code below is executed but not used | |
Console.WriteLine("About to return 2 eagerly"); | |
result.Add(2); | |
return result; | |
} | |
IEnumerable<int> LazyEvaluation() | |
{ | |
Console.WriteLine("About to return 1 lazily"); | |
yield return 1; | |
//Execution stops here | |
Console.WriteLine("About to return 2 lazily"); | |
yield return 2; | |
} | |
ReadFirstValue(EagerEvaluation()); | |
Console.ReadLine(); | |
ReadFirstValue(LazyEvaluation()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment