SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
UniRx - Reactive Extensions for Unity
Yoshifumi Kawai - @neuecc
Self Introduction
@Work
CTO/Director at Grani, Inc
Grani is top social game developer in Japan
C# 5.0 + .NET Framework 4.5 + ASP.NET MVC 5
@Private
Microsoft MVP for Visual C#
Web http://neue.cc/ (JPN)
Twitter @neuecc (JPN)
linq.js - http://linqjs.codeplex.com/ LINQ to Objects for JavaScript
Async in Unity
Coroutine is not good practice for asynchronous operation
Async in Unity
Network operation is awaitable by yield return
Good by callback hell!
It’s good! good?
I have never thought it is good.
IEnumerator OnMouseDown()
{
var www = new WWW("http://bing.com/");
yield return www; // await
Debug.Log(www.text);
}
Problem of yield
can’t return result
can’t handle exception
IEnumerator GetGoogle()
{
var www = new WWW("http://google.com/");
yield return www;
// can’t return www.text
}
IEnumerator OnMouseDown()
{
// this code is compiler error
// yield can’t surround with try-catch
try
{
yield return StartCoroutine(GetGoogle());
}
catch
{
}
}
It cause operation can’t separate.
We have to write on one IEnumerator.
Or Callback
IEnumerator GetGoogle(Action<string> onCompleted, Action<Exception> onError)
{
var www = new WWW("http://google.com/");
yield return www;
if (!www.error) onError(new Exception(www.error));
else onCompleted(www.text);
}
IEnumerator OnMouseDown()
{
string result;
Exception error;
yield return StartCoroutine(GetGoogle(x => result = x, x => error = x));
string result2;
Exception error2;
yield return StartCoroutine(GetGoogle(x => result2 = x, x => error2 = x));
}
Welcome to the callback hell!
(We can await by yield but terrible yet)
async Task<string> RunAsync()
{
try
{
var v = await new HttpClient().GetStringAsync("http://google.co.jp/");
var v2 = await new HttpClient().GetStringAsync("http://google.co.jp/");
return v + v2;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}
}
If so C# 5.0(async/await)
yield(await) can receive return value
We can handle exception by try-catch
Async method can return result
Unity 5.0
Will be released on 2014 fall
But Mono runtime is not renewed
C# is still old(3.0)
async has not come.
IL2CPP - The future of scripting in Unity
http://blogs.unity3d.com/2014/05/20/the-future-of-scripting-in-
unity/
It’s future.
Reactive Programming
About Reactive Programming
Recently attracted architecture style
The Rective Manifesto http://www.reactivemanifesto.org/
Reactive Streams http://www.reactive-streams.org/
Principles of Reactive Programming
https://www.coursera.org/course/reactive
Martin Odersky(Creator of Scala)
Eric Meijer(Creator of Reactive Extensions)
Roland Kuhn(Akka Tech Lead)
Gartner’s Hype Cycle
2013 Application Architecture/Application Development
On the Rise - Reactive Programming
Reactive Extensions
Reactive Programming on .NET
https://rx.codeplex.com
Project of Microsoft, OSS
LINQ to events, asynchronous and more.
Port to other languages
RxJava(by Netflix)
https://github.com/Netflix/RxJava 2070 Stars
RxJS(by Microsoft)
https://github.com/Reactive-Extensions/RxJS 1021 Stars
UniRx - Reactive Extensions for Unity
Why UniRx?
Official Rx is great impl but too heavy, can’t work old C#
and can’t avoid iOS AOT trap.
RxUnity is re-implementation of RxNet for Unity
and several Unity specified utilities(Scheduler, ObservableWWW, etc)
Available Now
GitHub - https://github.com/neuecc/UniRx/
On Unity AssetStore(FREE)
http://u3d.as/content/neuecc/uni-rx-reactive-extensions-for-
unity/7tT
Curing Your Asynchronous
Programming Blues
Rx saves your life & codes
UnityAsync with Rx
// x completed then go y and completed z, async flow by LINQ Query Expression
var query = from x in ObservableWWW.Get("http://google.co.jp/")
from y in ObservableWWW.Get(x)
from z in ObservableWWW.Get(y)
select new { x, y, z };
// Subscribe = “finally callback“(can avoid nested callback)
query.Subscribe(x => Debug.Log(x), ex => Debug.LogException(ex));
// or convert to Coroutine and await(ToCoroutine is yieldable!)
yield return StartCoroutine(query.Do(x => Debug.Log(x)).ToCoroutine());
etc, etc....
// Parallel run A and B
var query = Observable.Zip(
ObservableWWW.Get("http://google.co.jp/"),
ObservableWWW.Get("http://bing.com/"),
(google, bing) => new { google, bing });
// Retry on error
var cancel = ObservableWWW.Get("http://hogehgoe")
.OnErrorRetry((Exception ex) => Debug.LogException(ex),
retryCount: 3, delay: TimeSpan.FromSeconds(1))
.Subscribe(Debug.Log);
// Cancel is call Dispose of subscribed value
cancel.Dispose();
// etc, etc, Rx has over 100 operators(methods) for method chain
// you can control all execution flow of sync and async
ObservableWWW is included in
RxUnity, it is wrapped WWW, all
method return IObservable
Orchestrate MultiThreading
and LINQ to MonoBehaviour Message Events
UniRx solves MultiThreading problems
// heavy work start on other thread(or specified scheduler)
var heavyMethod1 = Observable.Start(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
return 1;
});
var heavyMethod2 = Observable.Start(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(3));
return 2;
});
// Parallel work and concatenate by Zip
heavyMethod1.Zip(heavyMethod2, (x, y) => new { x, y })
.ObserveOnMainThread() // return to MainThread
.Subscribe(x =>
{
// you can access GameObject
(GameObject.Find("myGuiText")).guiText.text = x.ToString();
});
join other thread
ObserveOnMainThread
is return to MainThread
and after flow can access
GameObject
easily cancel(call Dispose
of subscribed value) etc,
many methods supports
multi thread programming
AsyncA AsyncB
SelectMany – linear join
AsyncA
Zip – parallel join
AsyncB
Result
AsyncA AsyncB
AsyncC
Result
AsyncA().SelectMany(a => AsyncB(a))
.Zip(AsyncC(), (b, c) => new { b, c });
SelectMany + Zip – Compose Sample
var asyncQuery = from a in AsyncA()
from b in AsyncB(a)
from c in AsyncC(a, b)
select new { a, b, c };
multiplex from(SelectMany)
AsyncA AsyncB AsyncC Result
Extra Gems
Extra methods only for Unity
// Observable.EveryUpdate/FixedUpdate
// produce value on every frame
Observable.EveryUpdate()
.Subscribe(_ => Debug.Log(DateTime.Now.ToString()));
// ObservableMonoBehaviour
public class Hoge : ObservableMonoBehaviour
{
public override void Awake()
{
// All MessageEvent are IObservable<T>
var query = this.OnMouseDownAsObservable()
.SelectMany(_ => this.OnMouseDragAsObservable())
.TakeUntil(this.OnMouseUpAsObservable());
}
}
Unity用の各支援メソッド
// prepare container
public class LogCallback
{
public string Condition;
public string StackTrace;
public UnityEngine.LogType LogType;
}
public static class LogHelper
{
static Subject<LogCallback> subject;
public static IObservable<LogCallback> LogCallbackAsObservable()
{
if (subject == null)
{
subject = new Subject<LogCallback>();
// publish to subject in callback
UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
{
subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = ty
});
}
return subject.AsObservable();
}
}
Convert Unity Callback to IObservable<T>
Unity用の各支援メソッド
// prepare container
public class LogCallback
{
public string Condition;
public string StackTrace;
public UnityEngine.LogType LogType;
}
public static class LogHelper
{
static Subject<LogCallback> subject;
public static IObservable<LogCallback> LogCallbackAsObservable()
{
if (subject == null)
{
subject = new Subject<LogCallback>();
// publish to subject in callback
UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
{
subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = ty
});
}
return subject.AsObservable();
}
}
Convert Unity Callback to IObservable<T>
// It’s separatable, composable, etc.
LogHelper.LogCallbackAsObservable()
.Where(x => x.LogType == LogType.Warning)
.Subscribe();
LogHelper.LogCallbackAsObservable()
.Where(x => x.LogType == LogType.Error)
.Subscribe();
Conclusion
Conclusion
IEnumerator for Async is bad
and C# 5.0(async/await) hasn’t come
Then UniRx
Why Rx, not Task?
Task is poor function without await
And for MultiThreading, Event Operation, any more
Available Now FREE
GitHub - https://github.com/neuecc/UniRx/
AssetStore – http://u3d.as/content/neuecc/uni-rx-reactive-
extensions-for-unity/7tT

Contenu connexe

Tendances

ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
Yoshifumi Kawai
 

Tendances (20)

【Unite Tokyo 2019】Unity Test Runnerを活用して内部品質を向上しよう
【Unite Tokyo 2019】Unity Test Runnerを活用して内部品質を向上しよう【Unite Tokyo 2019】Unity Test Runnerを活用して内部品質を向上しよう
【Unite Tokyo 2019】Unity Test Runnerを活用して内部品質を向上しよう
 
ゲーム開発初心者の僕がUnity + WebSocketで何か作ってみた
ゲーム開発初心者の僕がUnity + WebSocketで何か作ってみたゲーム開発初心者の僕がUnity + WebSocketで何か作ってみた
ゲーム開発初心者の僕がUnity + WebSocketで何か作ってみた
 
Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019Best practices: Async vs. coroutines - Unite Copenhagen 2019
Best practices: Async vs. coroutines - Unite Copenhagen 2019
 
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
 
【Unite Tokyo 2018】さては非同期だなオメー!async/await完全に理解しよう
【Unite Tokyo 2018】さては非同期だなオメー!async/await完全に理解しよう【Unite Tokyo 2018】さては非同期だなオメー!async/await完全に理解しよう
【Unite Tokyo 2018】さては非同期だなオメー!async/await完全に理解しよう
 
NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#NextGen Server/Client Architecture - gRPC + Unity + C#
NextGen Server/Client Architecture - gRPC + Unity + C#
 
C# ゲームプログラミングはホントにメモリのことに無頓着でいいの?
C# ゲームプログラミングはホントにメモリのことに無頓着でいいの?C# ゲームプログラミングはホントにメモリのことに無頓着でいいの?
C# ゲームプログラミングはホントにメモリのことに無頓着でいいの?
 
【Unite Tokyo 2019】今すぐ現場で覚えておきたい最適化技法 ~「ゲシュタルト・オーディン」開発における最適化事例~
【Unite Tokyo 2019】今すぐ現場で覚えておきたい最適化技法 ~「ゲシュタルト・オーディン」開発における最適化事例~【Unite Tokyo 2019】今すぐ現場で覚えておきたい最適化技法 ~「ゲシュタルト・オーディン」開発における最適化事例~
【Unite Tokyo 2019】今すぐ現場で覚えておきたい最適化技法 ~「ゲシュタルト・オーディン」開発における最適化事例~
 
UIElements+UI BuilderでEditor拡張を作ろう
UIElements+UI BuilderでEditor拡張を作ろうUIElements+UI BuilderでEditor拡張を作ろう
UIElements+UI BuilderでEditor拡張を作ろう
 
非同期処理の基礎
非同期処理の基礎非同期処理の基礎
非同期処理の基礎
 
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
ライブラリ作成のすゝめ - 事例から見る個人OSS開発の効能
 
【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方
【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方
【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方
 
【Unity道場】AssetGraph入門 〜ノードを駆使しててUnityの面倒な手作業を自動化する方法〜
【Unity道場】AssetGraph入門 〜ノードを駆使しててUnityの面倒な手作業を自動化する方法〜【Unity道場】AssetGraph入門 〜ノードを駆使しててUnityの面倒な手作業を自動化する方法〜
【Unity道場】AssetGraph入門 〜ノードを駆使しててUnityの面倒な手作業を自動化する方法〜
 
大規模ゲーム開発における build 高速化と安定化
大規模ゲーム開発における build 高速化と安定化大規模ゲーム開発における build 高速化と安定化
大規模ゲーム開発における build 高速化と安定化
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
Unity開発で使える設計の話+Zenjectの紹介
Unity開発で使える設計の話+Zenjectの紹介Unity開発で使える設計の話+Zenjectの紹介
Unity開発で使える設計の話+Zenjectの紹介
 
A quick tour of the Cysharp OSS
A quick tour of the Cysharp OSSA quick tour of the Cysharp OSS
A quick tour of the Cysharp OSS
 
【Unite 2018 Tokyo】60fpsのその先へ!スマホの物量限界に挑んだSTG「アカとブルー」の開発設計
【Unite 2018 Tokyo】60fpsのその先へ!スマホの物量限界に挑んだSTG「アカとブルー」の開発設計【Unite 2018 Tokyo】60fpsのその先へ!スマホの物量限界に挑んだSTG「アカとブルー」の開発設計
【Unite 2018 Tokyo】60fpsのその先へ!スマホの物量限界に挑んだSTG「アカとブルー」の開発設計
 
最速C# 7.x
最速C# 7.x最速C# 7.x
最速C# 7.x
 
【Unite 2018 Tokyo】『CARAVAN STORIES』のアセットバンドル事例
【Unite 2018 Tokyo】『CARAVAN STORIES』のアセットバンドル事例【Unite 2018 Tokyo】『CARAVAN STORIES』のアセットバンドル事例
【Unite 2018 Tokyo】『CARAVAN STORIES』のアセットバンドル事例
 

Similaire à UniRx - Reactive Extensions for Unity(EN)

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
DIY- computer vision with GWT
DIY- computer vision with GWTDIY- computer vision with GWT
DIY- computer vision with GWT
Francesca Tosi
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
Lei Kang
 

Similaire à UniRx - Reactive Extensions for Unity(EN) (20)

Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
 
React native
React nativeReact native
React native
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.
 
DIY- computer vision with GWT
DIY- computer vision with GWTDIY- computer vision with GWT
DIY- computer vision with GWT
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Reactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event ProcessingReactive Programming by UniRx for Asynchronous & Event Processing
Reactive Programming by UniRx for Asynchronous & Event Processing
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on Android
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Modern frontend in react.js
Modern frontend in react.jsModern frontend in react.js
Modern frontend in react.js
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
 

Plus de Yoshifumi Kawai

Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニーUnity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
Yoshifumi Kawai
 
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
Yoshifumi Kawai
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
Yoshifumi Kawai
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Yoshifumi Kawai
 
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
Yoshifumi Kawai
 

Plus de Yoshifumi Kawai (20)

Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#Building the Game Server both API and Realtime via c#
Building the Game Server both API and Realtime via c#
 
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
Unityによるリアルタイム通信とMagicOnionによるC#大統一理論の実現
 
Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニーUnity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
Unity C#と.NET Core(MagicOnion) C# そしてKotlinによるハーモニー
 
Implements OpenTelemetry Collector in DotNet
Implements OpenTelemetry Collector in DotNetImplements OpenTelemetry Collector in DotNet
Implements OpenTelemetry Collector in DotNet
 
The Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnionThe Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnion
 
True Cloud Native Batch Workflow for .NET with MicroBatchFramework
True Cloud Native Batch Workflow for .NET with MicroBatchFrameworkTrue Cloud Native Batch Workflow for .NET with MicroBatchFramework
True Cloud Native Batch Workflow for .NET with MicroBatchFramework
 
Binary Reading in C#
Binary Reading in C#Binary Reading in C#
Binary Reading in C#
 
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
 
RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)RuntimeUnitTestToolkit for Unity(English)
RuntimeUnitTestToolkit for Unity(English)
 
RuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for UnityRuntimeUnitTestToolkit for Unity
RuntimeUnitTestToolkit for Unity
 
How to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterHow to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatter
 
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
ZeroFormatterに見るC#で最速のシリアライザを作成する100億の方法
 
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPCZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
ZeroFormatter/MagicOnion - Fastest C# Serializer/gRPC based C# RPC
 
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
What, Why, How Create OSS Libraries - 過去に制作した30のライブラリから見るC#コーディングテクニックと個人OSSの...
 
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
 
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
Photon Server Deep Dive - PhotonWireの実装から見つめるPhotonServerの基礎と応用
 
Clash of Oni Online - VR Multiplay Sword Action
Clash of Oni Online - VR Multiplay Sword Action Clash of Oni Online - VR Multiplay Sword Action
Clash of Oni Online - VR Multiplay Sword Action
 
LINQPad with LINQ to BigQuery - Desktop Client for BigQuery
LINQPad with LINQ to BigQuery - Desktop Client for BigQueryLINQPad with LINQ to BigQuery - Desktop Client for BigQuery
LINQPad with LINQ to BigQuery - Desktop Client for BigQuery
 
Metaprogramming Universe in C# - 実例に見るILからRoslynまでの活用例
Metaprogramming Universe in C# - 実例に見るILからRoslynまでの活用例Metaprogramming Universe in C# - 実例に見るILからRoslynまでの活用例
Metaprogramming Universe in C# - 実例に見るILからRoslynまでの活用例
 
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
 

Dernier

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

UniRx - Reactive Extensions for Unity(EN)

  • 1. UniRx - Reactive Extensions for Unity Yoshifumi Kawai - @neuecc
  • 2. Self Introduction @Work CTO/Director at Grani, Inc Grani is top social game developer in Japan C# 5.0 + .NET Framework 4.5 + ASP.NET MVC 5 @Private Microsoft MVP for Visual C# Web http://neue.cc/ (JPN) Twitter @neuecc (JPN) linq.js - http://linqjs.codeplex.com/ LINQ to Objects for JavaScript
  • 3. Async in Unity Coroutine is not good practice for asynchronous operation
  • 4. Async in Unity Network operation is awaitable by yield return Good by callback hell! It’s good! good? I have never thought it is good. IEnumerator OnMouseDown() { var www = new WWW("http://bing.com/"); yield return www; // await Debug.Log(www.text); }
  • 5. Problem of yield can’t return result can’t handle exception IEnumerator GetGoogle() { var www = new WWW("http://google.com/"); yield return www; // can’t return www.text } IEnumerator OnMouseDown() { // this code is compiler error // yield can’t surround with try-catch try { yield return StartCoroutine(GetGoogle()); } catch { } } It cause operation can’t separate. We have to write on one IEnumerator.
  • 6. Or Callback IEnumerator GetGoogle(Action<string> onCompleted, Action<Exception> onError) { var www = new WWW("http://google.com/"); yield return www; if (!www.error) onError(new Exception(www.error)); else onCompleted(www.text); } IEnumerator OnMouseDown() { string result; Exception error; yield return StartCoroutine(GetGoogle(x => result = x, x => error = x)); string result2; Exception error2; yield return StartCoroutine(GetGoogle(x => result2 = x, x => error2 = x)); } Welcome to the callback hell! (We can await by yield but terrible yet)
  • 7. async Task<string> RunAsync() { try { var v = await new HttpClient().GetStringAsync("http://google.co.jp/"); var v2 = await new HttpClient().GetStringAsync("http://google.co.jp/"); return v + v2; } catch (Exception ex) { Debug.WriteLine(ex); throw; } } If so C# 5.0(async/await) yield(await) can receive return value We can handle exception by try-catch Async method can return result
  • 8. Unity 5.0 Will be released on 2014 fall But Mono runtime is not renewed C# is still old(3.0) async has not come. IL2CPP - The future of scripting in Unity http://blogs.unity3d.com/2014/05/20/the-future-of-scripting-in- unity/ It’s future.
  • 10. About Reactive Programming Recently attracted architecture style The Rective Manifesto http://www.reactivemanifesto.org/ Reactive Streams http://www.reactive-streams.org/ Principles of Reactive Programming https://www.coursera.org/course/reactive Martin Odersky(Creator of Scala) Eric Meijer(Creator of Reactive Extensions) Roland Kuhn(Akka Tech Lead)
  • 11. Gartner’s Hype Cycle 2013 Application Architecture/Application Development On the Rise - Reactive Programming
  • 12. Reactive Extensions Reactive Programming on .NET https://rx.codeplex.com Project of Microsoft, OSS LINQ to events, asynchronous and more. Port to other languages RxJava(by Netflix) https://github.com/Netflix/RxJava 2070 Stars RxJS(by Microsoft) https://github.com/Reactive-Extensions/RxJS 1021 Stars
  • 13. UniRx - Reactive Extensions for Unity Why UniRx? Official Rx is great impl but too heavy, can’t work old C# and can’t avoid iOS AOT trap. RxUnity is re-implementation of RxNet for Unity and several Unity specified utilities(Scheduler, ObservableWWW, etc) Available Now GitHub - https://github.com/neuecc/UniRx/ On Unity AssetStore(FREE) http://u3d.as/content/neuecc/uni-rx-reactive-extensions-for- unity/7tT
  • 14. Curing Your Asynchronous Programming Blues Rx saves your life & codes
  • 15. UnityAsync with Rx // x completed then go y and completed z, async flow by LINQ Query Expression var query = from x in ObservableWWW.Get("http://google.co.jp/") from y in ObservableWWW.Get(x) from z in ObservableWWW.Get(y) select new { x, y, z }; // Subscribe = “finally callback“(can avoid nested callback) query.Subscribe(x => Debug.Log(x), ex => Debug.LogException(ex)); // or convert to Coroutine and await(ToCoroutine is yieldable!) yield return StartCoroutine(query.Do(x => Debug.Log(x)).ToCoroutine());
  • 16. etc, etc.... // Parallel run A and B var query = Observable.Zip( ObservableWWW.Get("http://google.co.jp/"), ObservableWWW.Get("http://bing.com/"), (google, bing) => new { google, bing }); // Retry on error var cancel = ObservableWWW.Get("http://hogehgoe") .OnErrorRetry((Exception ex) => Debug.LogException(ex), retryCount: 3, delay: TimeSpan.FromSeconds(1)) .Subscribe(Debug.Log); // Cancel is call Dispose of subscribed value cancel.Dispose(); // etc, etc, Rx has over 100 operators(methods) for method chain // you can control all execution flow of sync and async ObservableWWW is included in RxUnity, it is wrapped WWW, all method return IObservable
  • 17. Orchestrate MultiThreading and LINQ to MonoBehaviour Message Events
  • 18. UniRx solves MultiThreading problems // heavy work start on other thread(or specified scheduler) var heavyMethod1 = Observable.Start(() => { Thread.Sleep(TimeSpan.FromSeconds(1)); return 1; }); var heavyMethod2 = Observable.Start(() => { Thread.Sleep(TimeSpan.FromSeconds(3)); return 2; }); // Parallel work and concatenate by Zip heavyMethod1.Zip(heavyMethod2, (x, y) => new { x, y }) .ObserveOnMainThread() // return to MainThread .Subscribe(x => { // you can access GameObject (GameObject.Find("myGuiText")).guiText.text = x.ToString(); }); join other thread ObserveOnMainThread is return to MainThread and after flow can access GameObject easily cancel(call Dispose of subscribed value) etc, many methods supports multi thread programming
  • 19. AsyncA AsyncB SelectMany – linear join AsyncA Zip – parallel join AsyncB Result
  • 20. AsyncA AsyncB AsyncC Result AsyncA().SelectMany(a => AsyncB(a)) .Zip(AsyncC(), (b, c) => new { b, c }); SelectMany + Zip – Compose Sample
  • 21. var asyncQuery = from a in AsyncA() from b in AsyncB(a) from c in AsyncC(a, b) select new { a, b, c }; multiplex from(SelectMany) AsyncA AsyncB AsyncC Result
  • 23. Extra methods only for Unity // Observable.EveryUpdate/FixedUpdate // produce value on every frame Observable.EveryUpdate() .Subscribe(_ => Debug.Log(DateTime.Now.ToString())); // ObservableMonoBehaviour public class Hoge : ObservableMonoBehaviour { public override void Awake() { // All MessageEvent are IObservable<T> var query = this.OnMouseDownAsObservable() .SelectMany(_ => this.OnMouseDragAsObservable()) .TakeUntil(this.OnMouseUpAsObservable()); } }
  • 24. Unity用の各支援メソッド // prepare container public class LogCallback { public string Condition; public string StackTrace; public UnityEngine.LogType LogType; } public static class LogHelper { static Subject<LogCallback> subject; public static IObservable<LogCallback> LogCallbackAsObservable() { if (subject == null) { subject = new Subject<LogCallback>(); // publish to subject in callback UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) => { subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = ty }); } return subject.AsObservable(); } } Convert Unity Callback to IObservable<T>
  • 25. Unity用の各支援メソッド // prepare container public class LogCallback { public string Condition; public string StackTrace; public UnityEngine.LogType LogType; } public static class LogHelper { static Subject<LogCallback> subject; public static IObservable<LogCallback> LogCallbackAsObservable() { if (subject == null) { subject = new Subject<LogCallback>(); // publish to subject in callback UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) => { subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = ty }); } return subject.AsObservable(); } } Convert Unity Callback to IObservable<T> // It’s separatable, composable, etc. LogHelper.LogCallbackAsObservable() .Where(x => x.LogType == LogType.Warning) .Subscribe(); LogHelper.LogCallbackAsObservable() .Where(x => x.LogType == LogType.Error) .Subscribe();
  • 27. Conclusion IEnumerator for Async is bad and C# 5.0(async/await) hasn’t come Then UniRx Why Rx, not Task? Task is poor function without await And for MultiThreading, Event Operation, any more Available Now FREE GitHub - https://github.com/neuecc/UniRx/ AssetStore – http://u3d.as/content/neuecc/uni-rx-reactive- extensions-for-unity/7tT