Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active February 1, 2017 08:44
Show Gist options
  • Select an option

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

Select an option

Save ichiroku11/e1805cd5633a7e465fdc8ad0241bfda4 to your computer and use it in GitHub Desktop.
Observable.Startを試した
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp {
class Program {
static void Main(string[] args) {
var stopwatch = Stopwatch.StartNew();
// デリゲートを非同期で実行してObservableを作る
var observable = Observable.Start(() => {
// このFuncはすぐ呼ばれる
Console.WriteLine($"{stopwatch.Elapsed}| Start");
Task.Delay(2000).Wait();
Console.WriteLine($"{stopwatch.Elapsed}| End");
return 99;
});
Task.Delay(1000).Wait();
// Subscribeしたタイミングでは、Observable.Startで呼び出しFuncが終了していない
// Funcが終了するとOnNext、OnCompletedが呼ばれる
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"));
Task.Delay(2000).Wait();
// すでにFuncが終了している
// Subscribeの直後にOnNext、OnCompletedが呼ばれる
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:00.0280716| Start
00:00:01.0321630| Subscribe#1
00:00:02.0369086| End
00:00:02.0407652| Subscribe#1.OnNext(99)
00:00:02.0430583| Subscribe#1.OnCompleted
00:00:03.0507230| Subscribe#2
00:00:03.0523044| Subscribe#2.OnNext(99)
00:00:03.0540312| Subscribe#2.OnCompleted
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment