Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created February 2, 2017 03:19
Show Gist options
  • Select an option

  • Save ichiroku11/19979ff13b24e7e2a57ece83294ff1c9 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/19979ff13b24e7e2a57ece83294ff1c9 to your computer and use it in GitHub Desktop.
Observable.ToAsyncとObservable.Deferを試した
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp {
class Program {
static void Main(string[] args) {
var stopwatch = Stopwatch.StartNew();
var sequence = 0;
// デリゲートを非同期実行するObservableを生成するFunc
var func = Observable.ToAsync(() => {
var id = Interlocked.Increment(ref sequence);
Console.WriteLine($"{stopwatch.Elapsed}| ToAsync#{id} Start");
Task.Delay(2000).Wait();
Console.WriteLine($"{stopwatch.Elapsed}| ToAsync#{id} End");
return 99;
});
Task.Delay(1000).Wait(); // ToAsyncで指定したデリゲートはまだ実行されない
// Subscribeされるたびに実行されるObservableを生成
// 実行されるのはfuncで生成されるObservableの(ToAsyncで指定した)デリゲート
Console.WriteLine($"{stopwatch.Elapsed}| Defer");
var observable = Observable.Defer(func);
Task.Delay(1000).Wait(); // ToAsyncで指定したデリゲートはまだ実行されない
// SubscribeするとToAsyncで指定したデリゲートが実行される
Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#1");
observable.Subscribe(
value => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#1.OnNext({value})"),
error => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#1.OnError({error})"),
() => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#1.OnCompleted"));
// SubscribeするとToAsyncで指定したデリゲートが実行される
Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#2");
observable.Subscribe(
value => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#2.OnNext({value})"),
error => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#2.OnError({error})"),
() => Console.WriteLine($"{stopwatch.Elapsed}| Subscribe#2.OnCompleted"));
Console.ReadLine();
}
// 実行結果
/*
00:00:01.0308233| Defer
00:00:02.0330955| Subscribe#1
00:00:02.0500948| ToAsync#1 Start
00:00:02.0511282| Subscribe#2
00:00:02.0517084| ToAsync#2 Start
00:00:04.0511973| ToAsync#1 End
00:00:04.0529325| Subscribe#1.OnNext(99)
00:00:04.0539547| Subscribe#1.OnCompleted
00:00:04.0572061| ToAsync#2 End
00:00:04.0578530| Subscribe#2.OnNext(99)
00:00:04.0586264| Subscribe#2.OnCompleted
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment