Created
April 12, 2012 01:58
-
-
Save baralong/2364244 to your computer and use it in GitHub Desktop.
2 Alternatives for getting an Observable from a Stream
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
IObservable<string> ObserveStringStream(Stream inputStream) | |
{ | |
var streamReader = new StreamReader(inputStream); | |
return ReadLoop(streamReader).ToObservable(Scheduler.ThreadPool); | |
} | |
private IEnumerable<string> ReadLoop(StreamReader reader) | |
{ | |
while (true) | |
{ | |
var line = reader.ReadLine(); | |
if (line != null) | |
{ | |
yield return line; | |
} | |
else | |
{ | |
yield break; | |
} | |
} | |
} |
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
IObservable<string> ObserveStringStream(Stream inputStream) | |
{ | |
var streamReader = new StreamReader(inputStream); | |
return Observable.Create<string>(observer => Scheduler.ThreadPool.Schedule(() => ReadLoop(streamReader, observer))); | |
} | |
private void ReadLoop(StreamReader reader, IObserver<string> observer) | |
{ | |
while (true) | |
{ | |
try | |
{ | |
var line = reader.ReadLine(); | |
if (line != null) | |
{ | |
observer.OnNext(line); | |
} | |
else | |
{ | |
observer.OnCompleted(); | |
break; | |
} | |
} | |
catch (Exception ex) | |
{ | |
observer.OnError(ex); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two version of generating a string observable from a stream. The old version has been in prod for ages and works well, the new version has only been played with a little in linqpad. Any reason to prefer the old version to the new? Any reason to prefer the new to the old, apart from being cleaner?