This commit is contained in:
liuyu 2024-07-31 14:52:38 +08:00
commit 75d1e80eb0
534 changed files with 40281 additions and 66 deletions

85
.gitignore vendored
View File

@ -1,10 +1,75 @@
Temp
UserSettings
.vsconfig
Assembly-CSharp.csproj
Assembly-CSharp-Editor.csproj
YanCheng_Metrology.sln
Library
Logs
obj
.vs
# ---> Unity
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore
#
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/
# MemoryCaptures can get excessive in size.
# They also could contain extremely sensitive data
/[Mm]emoryCaptures/
# Recordings can get excessive in size
/[Rr]ecordings/
# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*
# Autogenerated Jetbrains Rider plugin
/[Aa]ssets/Plugins/Editor/JetBrains*
# Visual Studio cache directory
.vs/
.idea/
# Gradle cache directory
.gradle/
# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db
# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta
# Unity3D generated file on crash reports
sysinfo.txt
# Builds
*.apk
*.aab
*.unitypackage
*.app
# Crashlytics generated file
crashlytics-build.properties
# Packed Addressables
/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*
# Temporary auto-generated Android Assets
/[Aa]ssets/[Ss]treamingAssets/aa.meta
/[Aa]ssets/[Ss]treamingAssets/aa/*

View File

@ -1,18 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 93888e21026cd284ba1b8c01eee54213
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1ff3a4a224e9fbf44b002da202c55191
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ed804b5e414d1ed4597e893b7e4c2b9e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace UniRx
{
public static class WebRequestExtensions
{
static IObservable<TResult> AbortableDeferredAsyncRequest<TResult>(Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, TResult> end, WebRequest request)
{
var result = Observable.Create<TResult>(observer =>
{
var isCompleted = -1;
var subscription = Observable.FromAsyncPattern<TResult>(begin,
ar =>
{
try
{
Interlocked.Increment(ref isCompleted);
return end(ar);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.RequestCanceled) return default(TResult);
throw;
}
})()
.Subscribe(observer);
return Disposable.Create(() =>
{
if (Interlocked.Increment(ref isCompleted) == 0)
{
subscription.Dispose();
request.Abort();
}
});
});
return result;
}
public static IObservable<WebResponse> GetResponseAsObservable(this WebRequest request)
{
return AbortableDeferredAsyncRequest<WebResponse>(request.BeginGetResponse, request.EndGetResponse, request);
}
public static IObservable<HttpWebResponse> GetResponseAsObservable(this HttpWebRequest request)
{
return AbortableDeferredAsyncRequest<HttpWebResponse>(request.BeginGetResponse, ar => (HttpWebResponse)request.EndGetResponse(ar), request);
}
public static IObservable<Stream> GetRequestStreamAsObservable(this WebRequest request)
{
return AbortableDeferredAsyncRequest<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, request);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 457f0007b2c70e34e9929ec8f0e2c4e6
timeCreated: 1455373898
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fe886f6e4204cf64982e3910466be84b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,25 @@
using System;
using System.Collections;
namespace UniRx
{
public sealed class BooleanDisposable : IDisposable, ICancelable
{
public bool IsDisposed { get; private set; }
public BooleanDisposable()
{
}
internal BooleanDisposable(bool isDisposed)
{
IsDisposed = isDisposed;
}
public void Dispose()
{
if (!IsDisposed) IsDisposed = true;
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4ff95c6eb380ca248984d8c27c1244d0
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,67 @@
// original code from GitHub Reactive-Extensions/Rx.NET
// some modified.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#if (NETFX_CORE || NET_4_6 || NET_STANDARD_2_0 || UNITY_WSA_10_0)
using System;
using System.Threading;
namespace UniRx
{
/// <summary>
/// Represents a disposable resource that has an associated <seealso cref="T:System.Threading.CancellationToken"/> that will be set to the cancellation requested state upon disposal.
/// </summary>
public sealed class CancellationDisposable : ICancelable
{
private readonly CancellationTokenSource _cts;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses an existing <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
/// <param name="cts"><seealso cref="T:System.Threading.CancellationTokenSource"/> used for cancellation.</param>
/// <exception cref="ArgumentNullException"><paramref name="cts"/> is null.</exception>
public CancellationDisposable(CancellationTokenSource cts)
{
if (cts == null)
throw new ArgumentNullException("cts");
_cts = cts;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses a new <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
public CancellationDisposable()
: this(new CancellationTokenSource())
{
}
/// <summary>
/// Gets the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
/// </summary>
public CancellationToken Token
{
get { return _cts.Token; }
}
/// <summary>
/// Cancels the underlying <seealso cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
public void Dispose()
{
_cts.Cancel();
}
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public bool IsDisposed
{
get { return _cts.IsCancellationRequested; }
}
}
}
#endif

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6c675907554bfa24d8bd411f386e410d
timeCreated: 1475137543
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
// using System.Linq; do not use LINQ
using System.Text;
namespace UniRx
{
// copy, modified from Rx Official
public sealed class CompositeDisposable : ICollection<IDisposable>, IDisposable, ICancelable
{
private readonly object _gate = new object();
private bool _disposed;
private List<IDisposable> _disposables;
private int _count;
private const int SHRINK_THRESHOLD = 64;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CompositeDisposable"/> class with no disposables contained by it initially.
/// </summary>
public CompositeDisposable()
{
_disposables = new List<IDisposable>();
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CompositeDisposable"/> class with the specified number of disposables.
/// </summary>
/// <param name="capacity">The number of disposables that the new CompositeDisposable can initially store.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than zero.</exception>
public CompositeDisposable(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
_disposables = new List<IDisposable>(capacity);
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CompositeDisposable"/> class from a group of disposables.
/// </summary>
/// <param name="disposables">Disposables that will be disposed together.</param>
/// <exception cref="ArgumentNullException"><paramref name="disposables"/> is null.</exception>
public CompositeDisposable(params IDisposable[] disposables)
{
if (disposables == null)
throw new ArgumentNullException("disposables");
_disposables = new List<IDisposable>(disposables);
_count = _disposables.Count;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CompositeDisposable"/> class from a group of disposables.
/// </summary>
/// <param name="disposables">Disposables that will be disposed together.</param>
/// <exception cref="ArgumentNullException"><paramref name="disposables"/> is null.</exception>
public CompositeDisposable(IEnumerable<IDisposable> disposables)
{
if (disposables == null)
throw new ArgumentNullException("disposables");
_disposables = new List<IDisposable>(disposables);
_count = _disposables.Count;
}
/// <summary>
/// Gets the number of disposables contained in the CompositeDisposable.
/// </summary>
public int Count
{
get
{
return _count;
}
}
/// <summary>
/// Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
/// </summary>
/// <param name="item">Disposable to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
public void Add(IDisposable item)
{
if (item == null)
throw new ArgumentNullException("item");
var shouldDispose = false;
lock (_gate)
{
shouldDispose = _disposed;
if (!_disposed)
{
_disposables.Add(item);
_count++;
}
}
if (shouldDispose)
item.Dispose();
}
/// <summary>
/// Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
/// </summary>
/// <param name="item">Disposable to remove.</param>
/// <returns>true if found; false otherwise.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Remove(IDisposable item)
{
if (item == null)
throw new ArgumentNullException("item");
var shouldDispose = false;
lock (_gate)
{
if (!_disposed)
{
//
// List<T> doesn't shrink the size of the underlying array but does collapse the array
// by copying the tail one position to the left of the removal index. We don't need
// index-based lookup but only ordering for sequential disposal. So, instead of spending
// cycles on the Array.Copy imposed by Remove, we use a null sentinel value. We also
// do manual Swiss cheese detection to shrink the list if there's a lot of holes in it.
//
var i = _disposables.IndexOf(item);
if (i >= 0)
{
shouldDispose = true;
_disposables[i] = null;
_count--;
if (_disposables.Capacity > SHRINK_THRESHOLD && _count < _disposables.Capacity / 2)
{
var old = _disposables;
_disposables = new List<IDisposable>(_disposables.Capacity / 2);
foreach (var d in old)
if (d != null)
_disposables.Add(d);
}
}
}
}
if (shouldDispose)
item.Dispose();
return shouldDispose;
}
/// <summary>
/// Disposes all disposables in the group and removes them from the group.
/// </summary>
public void Dispose()
{
var currentDisposables = default(IDisposable[]);
lock (_gate)
{
if (!_disposed)
{
_disposed = true;
currentDisposables = _disposables.ToArray();
_disposables.Clear();
_count = 0;
}
}
if (currentDisposables != null)
{
foreach (var d in currentDisposables)
if (d != null)
d.Dispose();
}
}
/// <summary>
/// Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
/// </summary>
public void Clear()
{
var currentDisposables = default(IDisposable[]);
lock (_gate)
{
currentDisposables = _disposables.ToArray();
_disposables.Clear();
_count = 0;
}
foreach (var d in currentDisposables)
if (d != null)
d.Dispose();
}
/// <summary>
/// Determines whether the CompositeDisposable contains a specific disposable.
/// </summary>
/// <param name="item">Disposable to search for.</param>
/// <returns>true if the disposable was found; otherwise, false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Contains(IDisposable item)
{
if (item == null)
throw new ArgumentNullException("item");
lock (_gate)
{
return _disposables.Contains(item);
}
}
/// <summary>
/// Copies the disposables contained in the CompositeDisposable to an array, starting at a particular array index.
/// </summary>
/// <param name="array">Array to copy the contained disposables to.</param>
/// <param name="arrayIndex">Target index at which to copy the first disposable of the group.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than zero. -or - <paramref name="arrayIndex"/> is larger than or equal to the array length.</exception>
public void CopyTo(IDisposable[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
lock (_gate)
{
var disArray = new List<IDisposable>();
foreach (var item in _disposables)
{
if (item != null) disArray.Add(item);
}
Array.Copy(disArray.ToArray(), 0, array, arrayIndex, array.Length - arrayIndex);
}
}
/// <summary>
/// Always returns false.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an enumerator that iterates through the CompositeDisposable.
/// </summary>
/// <returns>An enumerator to iterate over the disposables.</returns>
public IEnumerator<IDisposable> GetEnumerator()
{
var res = new List<IDisposable>();
lock (_gate)
{
foreach (var d in _disposables)
{
if (d != null) res.Add(d);
}
}
return res.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the CompositeDisposable.
/// </summary>
/// <returns>An enumerator to iterate over the disposables.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public bool IsDisposed
{
get { return _disposed; }
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a0f9d923bd5f4cd47b39bdd83125de27
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
namespace UniRx
{
public sealed class DictionaryDisposable<TKey, TValue> : IDisposable, IDictionary<TKey, TValue>
where TValue : IDisposable
{
bool isDisposed = false;
readonly Dictionary<TKey, TValue> inner;
public DictionaryDisposable()
{
inner = new Dictionary<TKey, TValue>();
}
public DictionaryDisposable(IEqualityComparer<TKey> comparer)
{
inner = new Dictionary<TKey, TValue>(comparer);
}
public TValue this[TKey key]
{
get
{
lock (inner)
{
return inner[key];
}
}
set
{
lock (inner)
{
if (isDisposed) value.Dispose();
TValue oldValue;
if (TryGetValue(key, out oldValue))
{
oldValue.Dispose();
inner[key] = value;
}
else
{
inner[key] = value;
}
}
}
}
public int Count
{
get
{
lock (inner)
{
return inner.Count;
}
}
}
public Dictionary<TKey, TValue>.KeyCollection Keys
{
get
{
throw new NotSupportedException("please use .Select(x => x.Key).ToArray()");
}
}
public Dictionary<TKey, TValue>.ValueCollection Values
{
get
{
throw new NotSupportedException("please use .Select(x => x.Value).ToArray()");
}
}
public void Add(TKey key, TValue value)
{
lock (inner)
{
if (isDisposed)
{
value.Dispose();
return;
}
inner.Add(key, value);
}
}
public void Clear()
{
lock (inner)
{
foreach (var item in inner)
{
item.Value.Dispose();
}
inner.Clear();
}
}
public bool Remove(TKey key)
{
lock (inner)
{
TValue oldValue;
if (inner.TryGetValue(key, out oldValue))
{
var isSuccessRemove = inner.Remove(key);
if (isSuccessRemove)
{
oldValue.Dispose();
}
return isSuccessRemove;
}
else
{
return false;
}
}
}
public bool ContainsKey(TKey key)
{
lock (inner)
{
return inner.ContainsKey(key);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (inner)
{
return inner.TryGetValue(key, out value);
}
}
public Dictionary<TKey, TValue>.Enumerator GetEnumerator()
{
lock (inner)
{
return new Dictionary<TKey, TValue>(inner).GetEnumerator();
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
return ((ICollection<KeyValuePair<TKey, TValue>>)inner).IsReadOnly;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
lock (inner)
{
return new List<TKey>(inner.Keys);
}
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
lock (inner)
{
return new List<TValue>(inner.Values);
}
}
}
#if !UNITY_METRO
public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
lock (inner)
{
((System.Runtime.Serialization.ISerializable)inner).GetObjectData(info, context);
}
}
public void OnDeserialization(object sender)
{
lock (inner)
{
((System.Runtime.Serialization.IDeserializationCallback)inner).OnDeserialization(sender);
}
}
#endif
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
Add((TKey)item.Key, (TValue)item.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
lock (inner)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)inner).Contains(item);
}
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
lock (inner)
{
((ICollection<KeyValuePair<TKey, TValue>>)inner).CopyTo(array, arrayIndex);
}
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
lock (inner)
{
return new List<KeyValuePair<TKey, TValue>>((ICollection<KeyValuePair<TKey, TValue>>)inner).GetEnumerator();
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
public void Dispose()
{
lock (inner)
{
if (isDisposed) return;
isDisposed = true;
foreach (var item in inner)
{
item.Value.Dispose();
}
inner.Clear();
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 702939929fc84d544b12076b76aa73b5
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,76 @@
using System;
using System.Collections;
namespace UniRx
{
public static class Disposable
{
public static readonly IDisposable Empty = EmptyDisposable.Singleton;
public static IDisposable Create(Action disposeAction)
{
return new AnonymousDisposable(disposeAction);
}
public static IDisposable CreateWithState<TState>(TState state, Action<TState> disposeAction)
{
return new AnonymousDisposable<TState>(state, disposeAction);
}
class EmptyDisposable : IDisposable
{
public static EmptyDisposable Singleton = new EmptyDisposable();
private EmptyDisposable()
{
}
public void Dispose()
{
}
}
class AnonymousDisposable : IDisposable
{
bool isDisposed = false;
readonly Action dispose;
public AnonymousDisposable(Action dispose)
{
this.dispose = dispose;
}
public void Dispose()
{
if (!isDisposed)
{
isDisposed = true;
dispose();
}
}
}
class AnonymousDisposable<T> : IDisposable
{
bool isDisposed = false;
readonly T state;
readonly Action<T> dispose;
public AnonymousDisposable(T state, Action<T> dispose)
{
this.state = state;
this.dispose = dispose;
}
public void Dispose()
{
if (!isDisposed)
{
isDisposed = true;
dispose(state);
}
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 958f291bb8f434740a6d2c08ad5182a0
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace UniRx
{
public static partial class DisposableExtensions
{
/// <summary>Add disposable(self) to CompositeDisposable(or other ICollection). Return value is self disposable.</summary>
public static T AddTo<T>(this T disposable, ICollection<IDisposable> container)
where T : IDisposable
{
if (disposable == null) throw new ArgumentNullException("disposable");
if (container == null) throw new ArgumentNullException("container");
container.Add(disposable);
return disposable;
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 9c4757265ae105441bae71007cbd0184
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UniRx
{
public interface ICancelable : IDisposable
{
bool IsDisposed { get; }
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b5cd5b0b304c78345a49757b1f6f8ba8
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,69 @@
using System;
using System.Collections;
namespace UniRx
{
public sealed class MultipleAssignmentDisposable : IDisposable, ICancelable
{
static readonly BooleanDisposable True = new BooleanDisposable(true);
object gate = new object();
IDisposable current;
public bool IsDisposed
{
get
{
lock (gate)
{
return current == True;
}
}
}
public IDisposable Disposable
{
get
{
lock (gate)
{
return (current == True)
? UniRx.Disposable.Empty
: current;
}
}
set
{
var shouldDispose = false;
lock (gate)
{
shouldDispose = (current == True);
if (!shouldDispose)
{
current = value;
}
}
if (shouldDispose && value != null)
{
value.Dispose();
}
}
}
public void Dispose()
{
IDisposable old = null;
lock (gate)
{
if (current != True)
{
old = current;
current = True;
}
}
if (old != null) old.Dispose();
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: bb959083576ace749afd55c1e54b02d9
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,152 @@
// This code is borrwed from Rx Official and some modified.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace UniRx
{
/// <summary>
/// Represents a disposable resource that only disposes its underlying disposable resource when all <see cref="GetDisposable">dependent disposable objects</see> have been disposed.
/// </summary>
public sealed class RefCountDisposable : ICancelable
{
private readonly object _gate = new object();
private IDisposable _disposable;
private bool _isPrimaryDisposed;
private int _count;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.RefCountDisposable"/> class with the specified disposable.
/// </summary>
/// <param name="disposable">Underlying disposable.</param>
/// <exception cref="ArgumentNullException"><paramref name="disposable"/> is null.</exception>
public RefCountDisposable(IDisposable disposable)
{
if (disposable == null)
throw new ArgumentNullException("disposable");
_disposable = disposable;
_isPrimaryDisposed = false;
_count = 0;
}
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public bool IsDisposed
{
get { return _disposable == null; }
}
/// <summary>
/// Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
/// </summary>
/// <returns>A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Backward compat + non-trivial work for a property getter.")]
public IDisposable GetDisposable()
{
lock (_gate)
{
if (_disposable == null)
{
return Disposable.Empty;
}
else
{
_count++;
return new InnerDisposable(this);
}
}
}
/// <summary>
/// Disposes the underlying disposable only when all dependent disposables have been disposed.
/// </summary>
public void Dispose()
{
var disposable = default(IDisposable);
lock (_gate)
{
if (_disposable != null)
{
if (!_isPrimaryDisposed)
{
_isPrimaryDisposed = true;
if (_count == 0)
{
disposable = _disposable;
_disposable = null;
}
}
}
}
if (disposable != null)
disposable.Dispose();
}
private void Release()
{
var disposable = default(IDisposable);
lock (_gate)
{
if (_disposable != null)
{
_count--;
if (_isPrimaryDisposed)
{
if (_count == 0)
{
disposable = _disposable;
_disposable = null;
}
}
}
}
if (disposable != null)
disposable.Dispose();
}
sealed class InnerDisposable : IDisposable
{
private RefCountDisposable _parent;
object parentLock = new object();
public InnerDisposable(RefCountDisposable parent)
{
_parent = parent;
}
public void Dispose()
{
RefCountDisposable parent;
lock (parentLock)
{
parent = _parent;
_parent = null;
}
if (parent != null)
parent.Release();
}
}
}
public partial class Observable
{
static IObservable<T> AddRef<T>(IObservable<T> xs, RefCountDisposable r)
{
return Observable.Create<T>((IObserver<T> observer) => new CompositeDisposable(new IDisposable[]
{
r.GetDisposable(),
xs.Subscribe(observer)
}));
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2fb5a2cdb138579498eb20d8b7818ad8
timeCreated: 1455373898
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,46 @@
using System;
using System.Threading;
namespace UniRx
{
public sealed class ScheduledDisposable : ICancelable
{
private readonly IScheduler scheduler;
private volatile IDisposable disposable;
private int isDisposed = 0;
public ScheduledDisposable(IScheduler scheduler, IDisposable disposable)
{
this.scheduler = scheduler;
this.disposable = disposable;
}
public IScheduler Scheduler
{
get { return scheduler; }
}
public IDisposable Disposable
{
get { return disposable; }
}
public bool IsDisposed
{
get { return isDisposed != 0; }
}
public void Dispose()
{
Scheduler.Schedule(DisposeInner);
}
private void DisposeInner()
{
if (Interlocked.Increment(ref isDisposed) == 1)
{
disposable.Dispose();
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: db98ce742e859bd4e81db434c3ca3663
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,64 @@
using System;
using System.Collections;
namespace UniRx
{
public sealed class SerialDisposable : IDisposable, ICancelable
{
readonly object gate = new object();
IDisposable current;
bool disposed;
public bool IsDisposed { get { lock (gate) { return disposed; } } }
public IDisposable Disposable
{
get
{
return current;
}
set
{
var shouldDispose = false;
var old = default(IDisposable);
lock (gate)
{
shouldDispose = disposed;
if (!shouldDispose)
{
old = current;
current = value;
}
}
if (old != null)
{
old.Dispose();
}
if (shouldDispose && value != null)
{
value.Dispose();
}
}
}
public void Dispose()
{
var old = default(IDisposable);
lock (gate)
{
if (!disposed)
{
disposed = true;
old = current;
current = null;
}
}
if (old != null)
{
old.Dispose();
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 06fb064ad9e4d354ab15ff89f6343243
timeCreated: 1455373897
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,68 @@
using System;
using System.Collections;
namespace UniRx
{
// should be use Interlocked.CompareExchange for Threadsafe?
// but CompareExchange cause ExecutionEngineException on iOS.
// AOT...
// use lock instead
public sealed class SingleAssignmentDisposable : IDisposable, ICancelable
{
readonly object gate = new object();
IDisposable current;
bool disposed;
public bool IsDisposed { get { lock (gate) { return disposed; } } }
public IDisposable Disposable
{
get
{
return current;
}
set
{
var old = default(IDisposable);
bool alreadyDisposed;
lock (gate)
{
alreadyDisposed = disposed;
old = current;
if (!alreadyDisposed)
{
if (value == null) return;
current = value;
}
}
if (alreadyDisposed && value != null)
{
value.Dispose();
return;
}
if (old != null) throw new InvalidOperationException("Disposable is already set");
}
}
public void Dispose()
{
IDisposable old = null;
lock (gate)
{
if (!disposed)
{
disposed = true;
old = current;
current = null;
}
}
if (old != null) old.Dispose();
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7ec869f7548c62748ad57a5c86b2f6ba
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,277 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace UniRx
{
/// <summary>
/// Represents a group of disposable resources that are disposed together.
/// </summary>
public abstract class StableCompositeDisposable : ICancelable
{
/// <summary>
/// Creates a new group containing two disposable resources that are disposed together.
/// </summary>
/// <param name="disposable1">The first disposable resoruce to add to the group.</param>
/// <param name="disposable2">The second disposable resoruce to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable Create(IDisposable disposable1, IDisposable disposable2)
{
if (disposable1 == null) throw new ArgumentNullException("disposable1");
if (disposable2 == null) throw new ArgumentNullException("disposable2");
return new Binary(disposable1, disposable2);
}
/// <summary>
/// Creates a new group containing three disposable resources that are disposed together.
/// </summary>
/// <param name="disposable1">The first disposable resoruce to add to the group.</param>
/// <param name="disposable2">The second disposable resoruce to add to the group.</param>
/// <param name="disposable3">The third disposable resoruce to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable Create(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3)
{
if (disposable1 == null) throw new ArgumentNullException("disposable1");
if (disposable2 == null) throw new ArgumentNullException("disposable2");
if (disposable3 == null) throw new ArgumentNullException("disposable3");
return new Trinary(disposable1, disposable2, disposable3);
}
/// <summary>
/// Creates a new group containing four disposable resources that are disposed together.
/// </summary>
/// <param name="disposable1">The first disposable resoruce to add to the group.</param>
/// <param name="disposable2">The second disposable resoruce to add to the group.</param>
/// <param name="disposable3">The three disposable resoruce to add to the group.</param>
/// <param name="disposable4">The four disposable resoruce to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable Create(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3, IDisposable disposable4)
{
if (disposable1 == null) throw new ArgumentNullException("disposable1");
if (disposable2 == null) throw new ArgumentNullException("disposable2");
if (disposable3 == null) throw new ArgumentNullException("disposable3");
if (disposable4 == null) throw new ArgumentNullException("disposable4");
return new Quaternary(disposable1, disposable2, disposable3, disposable4);
}
/// <summary>
/// Creates a new group of disposable resources that are disposed together.
/// </summary>
/// <param name="disposables">Disposable resources to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable Create(params IDisposable[] disposables)
{
if (disposables == null) throw new ArgumentNullException("disposables");
return new NAry(disposables);
}
/// <summary>
/// Creates a new group of disposable resources that are disposed together. Array is not copied, it's unsafe but optimized.
/// </summary>
/// <param name="disposables">Disposable resources to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable CreateUnsafe(IDisposable[] disposables)
{
return new NAryUnsafe(disposables);
}
/// <summary>
/// Creates a new group of disposable resources that are disposed together.
/// </summary>
/// <param name="disposables">Disposable resources to add to the group.</param>
/// <returns>Group of disposable resources that are disposed together.</returns>
public static ICancelable Create(IEnumerable<IDisposable> disposables)
{
if (disposables == null) throw new ArgumentNullException("disposables");
return new NAry(disposables);
}
/// <summary>
/// Disposes all disposables in the group.
/// </summary>
public abstract void Dispose();
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public abstract bool IsDisposed
{
get;
}
class Binary : StableCompositeDisposable
{
int disposedCallCount = -1;
private volatile IDisposable _disposable1;
private volatile IDisposable _disposable2;
public Binary(IDisposable disposable1, IDisposable disposable2)
{
_disposable1 = disposable1;
_disposable2 = disposable2;
}
public override bool IsDisposed
{
get
{
return disposedCallCount != -1;
}
}
public override void Dispose()
{
if (Interlocked.Increment(ref disposedCallCount) == 0)
{
_disposable1.Dispose();
_disposable2.Dispose();
}
}
}
class Trinary : StableCompositeDisposable
{
int disposedCallCount = -1;
private volatile IDisposable _disposable1;
private volatile IDisposable _disposable2;
private volatile IDisposable _disposable3;
public Trinary(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3)
{
_disposable1 = disposable1;
_disposable2 = disposable2;
_disposable3 = disposable3;
}
public override bool IsDisposed
{
get
{
return disposedCallCount != -1;
}
}
public override void Dispose()
{
if (Interlocked.Increment(ref disposedCallCount) == 0)
{
_disposable1.Dispose();
_disposable2.Dispose();
_disposable3.Dispose();
}
}
}
class Quaternary : StableCompositeDisposable
{
int disposedCallCount = -1;
private volatile IDisposable _disposable1;
private volatile IDisposable _disposable2;
private volatile IDisposable _disposable3;
private volatile IDisposable _disposable4;
public Quaternary(IDisposable disposable1, IDisposable disposable2, IDisposable disposable3, IDisposable disposable4)
{
_disposable1 = disposable1;
_disposable2 = disposable2;
_disposable3 = disposable3;
_disposable4 = disposable4;
}
public override bool IsDisposed
{
get
{
return disposedCallCount != -1;
}
}
public override void Dispose()
{
if (Interlocked.Increment(ref disposedCallCount) == 0)
{
_disposable1.Dispose();
_disposable2.Dispose();
_disposable3.Dispose();
_disposable4.Dispose();
}
}
}
class NAry : StableCompositeDisposable
{
int disposedCallCount = -1;
private volatile List<IDisposable> _disposables;
public NAry(IDisposable[] disposables)
: this((IEnumerable<IDisposable>)disposables)
{
}
public NAry(IEnumerable<IDisposable> disposables)
{
_disposables = new List<IDisposable>(disposables);
//
// Doing this on the list to avoid duplicate enumeration of disposables.
//
if (_disposables.Contains(null)) throw new ArgumentException("Disposables can't contains null", "disposables");
}
public override bool IsDisposed
{
get
{
return disposedCallCount != -1;
}
}
public override void Dispose()
{
if (Interlocked.Increment(ref disposedCallCount) == 0)
{
foreach (var d in _disposables)
{
d.Dispose();
}
}
}
}
class NAryUnsafe : StableCompositeDisposable
{
int disposedCallCount = -1;
private volatile IDisposable[] _disposables;
public NAryUnsafe(IDisposable[] disposables)
{
_disposables = disposables;
}
public override bool IsDisposed
{
get
{
return disposedCallCount != -1;
}
}
public override void Dispose()
{
if (Interlocked.Increment(ref disposedCallCount) == 0)
{
var len = _disposables.Length;
for (int i = 0; i < len; i++)
{
_disposables[i].Dispose();
}
}
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3a9cd9fa22bc6a5439484581f5049cf8
timeCreated: 1455373898
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,140 @@
// original code from rx.codeplex.com
// some modified.
/* ------------------ */
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace UniRx
{
/// <summary>
/// Represents a .NET event invocation consisting of the strongly typed object that raised the event and the data that was generated by the event.
/// </summary>
/// <typeparam name="TSender">
/// The type of the sender that raised the event.
/// This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
/// </typeparam>
/// <typeparam name="TEventArgs">
/// The type of the event data generated by the event.
/// This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
/// </typeparam>
public interface IEventPattern<TSender, TEventArgs>
{
/// <summary>
/// Gets the sender object that raised the event.
/// </summary>
TSender Sender { get; }
/// <summary>
/// Gets the event data that was generated by the event.
/// </summary>
TEventArgs EventArgs { get; }
}
/// <summary>
/// Represents a .NET event invocation consisting of the weakly typed object that raised the event and the data that was generated by the event.
/// </summary>
/// <typeparam name="TEventArgs">The type of the event data generated by the event.</typeparam>
public class EventPattern<TEventArgs> : EventPattern<object, TEventArgs>
{
/// <summary>
/// Creates a new data representation instance of a .NET event invocation with the given sender and event data.
/// </summary>
/// <param name="sender">The sender object that raised the event.</param>
/// <param name="e">The event data that was generated by the event.</param>
public EventPattern(object sender, TEventArgs e)
: base(sender, e)
{
}
}
/// <summary>
/// Represents a .NET event invocation consisting of the strongly typed object that raised the event and the data that was generated by the event.
/// </summary>
/// <typeparam name="TSender">The type of the sender that raised the event.</typeparam>
/// <typeparam name="TEventArgs">The type of the event data generated by the event.</typeparam>
public class EventPattern<TSender, TEventArgs> : IEquatable<EventPattern<TSender, TEventArgs>>, IEventPattern<TSender, TEventArgs>
{
/// <summary>
/// Creates a new data representation instance of a .NET event invocation with the given sender and event data.
/// </summary>
/// <param name="sender">The sender object that raised the event.</param>
/// <param name="e">The event data that was generated by the event.</param>
public EventPattern(TSender sender, TEventArgs e)
{
Sender = sender;
EventArgs = e;
}
/// <summary>
/// Gets the sender object that raised the event.
/// </summary>
public TSender Sender { get; private set; }
/// <summary>
/// Gets the event data that was generated by the event.
/// </summary>
public TEventArgs EventArgs { get; private set; }
/// <summary>
/// Determines whether the current EventPattern&lt;TSender, TEventArgs&gt; object represents the same event as a specified EventPattern&lt;TSender, TEventArgs&gt; object.
/// </summary>
/// <param name="other">An object to compare to the current EventPattern&lt;TSender, TEventArgs&gt; object.</param>
/// <returns>true if both EventPattern&lt;TSender, TEventArgs&gt; objects represent the same event; otherwise, false.</returns>
public bool Equals(EventPattern<TSender, TEventArgs> other)
{
if (object.ReferenceEquals(null, other))
return false;
if (object.ReferenceEquals(this, other))
return true;
return EqualityComparer<TSender>.Default.Equals(Sender, other.Sender) && EqualityComparer<TEventArgs>.Default.Equals(EventArgs, other.EventArgs);
}
/// <summary>
/// Determines whether the specified System.Object is equal to the current EventPattern&lt;TSender, TEventArgs&gt;.
/// </summary>
/// <param name="obj">The System.Object to compare with the current EventPattern&lt;TSender, TEventArgs&gt;.</param>
/// <returns>true if the specified System.Object is equal to the current EventPattern&lt;TSender, TEventArgs&gt;; otherwise, false.</returns>
public override bool Equals(object obj)
{
return Equals(obj as EventPattern<TSender, TEventArgs>);
}
/// <summary>
/// Returns the hash code for the current EventPattern&lt;TSender, TEventArgs&gt; instance.
/// </summary>
/// <returns>A hash code for the current EventPattern&lt;TSender, TEventArgs&gt; instance.</returns>
public override int GetHashCode()
{
var x = EqualityComparer<TSender>.Default.GetHashCode(Sender);
var y = EqualityComparer<TEventArgs>.Default.GetHashCode(EventArgs);
return (x << 5) + (x ^ y);
}
/// <summary>
/// Determines whether two specified EventPattern&lt;TSender, TEventArgs&gt; objects represent the same event.
/// </summary>
/// <param name="first">The first EventPattern&lt;TSender, TEventArgs&gt; to compare, or null.</param>
/// <param name="second">The second EventPattern&lt;TSender, TEventArgs&gt; to compare, or null.</param>
/// <returns>true if both EventPattern&lt;TSender, TEventArgs&gt; objects represent the same event; otherwise, false.</returns>
public static bool operator ==(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second)
{
return object.Equals(first, second);
}
/// <summary>
/// Determines whether two specified EventPattern&lt;TSender, TEventArgs&gt; objects represent a different event.
/// </summary>
/// <param name="first">The first EventPattern&lt;TSender, TEventArgs&gt; to compare, or null.</param>
/// <param name="second">The second EventPattern&lt;TSender, TEventArgs&gt; to compare, or null.</param>
/// <returns>true if both EventPattern&lt;TSender, TEventArgs&gt; objects don't represent the same event; otherwise, false.</returns>
public static bool operator !=(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second)
{
return !object.Equals(first, second);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e4b797bfea1999a499309068b7d7a97e
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9701602494b9c474680dea36ff9153df
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,85 @@
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified
using System;
using System.Collections.Generic;
namespace UniRx.InternalUtil
{
/// <summary>
/// Asynchronous lock.
/// </summary>
internal sealed class AsyncLock : IDisposable
{
private readonly Queue<Action> queue = new Queue<Action>();
private bool isAcquired = false;
private bool hasFaulted = false;
/// <summary>
/// Queues the action for execution. If the caller acquires the lock and becomes the owner,
/// the queue is processed. If the lock is already owned, the action is queued and will get
/// processed by the owner.
/// </summary>
/// <param name="action">Action to queue for execution.</param>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
public void Wait(Action action)
{
if (action == null)
throw new ArgumentNullException("action");
var isOwner = false;
lock (queue)
{
if (!hasFaulted)
{
queue.Enqueue(action);
isOwner = !isAcquired;
isAcquired = true;
}
}
if (isOwner)
{
while (true)
{
var work = default(Action);
lock (queue)
{
if (queue.Count > 0)
work = queue.Dequeue();
else
{
isAcquired = false;
break;
}
}
try
{
work();
}
catch
{
lock (queue)
{
queue.Clear();
hasFaulted = true;
}
throw;
}
}
}
}
/// <summary>
/// Clears the work items in the queue and drops further work being queued.
/// </summary>
public void Dispose()
{
lock (queue)
{
queue.Clear();
hasFaulted = true;
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 23dbd656cfe9c5e47b02c3c263e476aa
timeCreated: 1455373897
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,23 @@
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UniRx.InternalUtil
{
internal interface ICancellableTaskCompletionSource
{
bool TrySetException(Exception exception);
bool TrySetCanceled();
}
internal class CancellableTaskCompletionSource<T> : TaskCompletionSource<T>, ICancellableTaskCompletionSource
{
}
}
#endif

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 586a284588716604aa845bedd54c2341
guid: 622c7ba8630c25b4c911cd1612ee0887
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -0,0 +1,15 @@
namespace UniRx.InternalUtil
{
using System;
internal static class ExceptionExtensions
{
public static void Throw(this Exception exception)
{
#if (NET_4_6 || NET_STANDARD_2_0)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception).Throw();
#endif
throw exception;
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 94d5d10805124b34c8b488ebf3f893eb
timeCreated: 1509016318
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,61 @@
using System;
namespace UniRx.InternalUtil
{
// ImmutableList is sometimes useful, use for public.
public class ImmutableList<T>
{
public static readonly ImmutableList<T> Empty = new ImmutableList<T>();
T[] data;
public T[] Data
{
get { return data; }
}
ImmutableList()
{
data = new T[0];
}
public ImmutableList(T[] data)
{
this.data = data;
}
public ImmutableList<T> Add(T value)
{
var newData = new T[data.Length + 1];
Array.Copy(data, newData, data.Length);
newData[data.Length] = value;
return new ImmutableList<T>(newData);
}
public ImmutableList<T> Remove(T value)
{
var i = IndexOf(value);
if (i < 0) return this;
var length = data.Length;
if (length == 1) return Empty;
var newData = new T[length - 1];
Array.Copy(data, 0, newData, 0, i);
Array.Copy(data, i + 1, newData, i, length - i - 1);
return new ImmutableList<T>(newData);
}
public int IndexOf(T value)
{
for (var i = 0; i < data.Length; ++i)
{
// ImmutableList only use for IObserver(no worry for boxed)
if (object.Equals(data[i], value)) return i;
}
return -1;
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dbafd8a41f556ec40b4bbd46fca2e85c
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UniRx.InternalUtil
{
public class ListObserver<T> : IObserver<T>
{
private readonly ImmutableList<IObserver<T>> _observers;
public ListObserver(ImmutableList<IObserver<T>> observers)
{
_observers = observers;
}
public void OnCompleted()
{
var targetObservers = _observers.Data;
for (int i = 0; i < targetObservers.Length; i++)
{
targetObservers[i].OnCompleted();
}
}
public void OnError(Exception error)
{
var targetObservers = _observers.Data;
for (int i = 0; i < targetObservers.Length; i++)
{
targetObservers[i].OnError(error);
}
}
public void OnNext(T value)
{
var targetObservers = _observers.Data;
for (int i = 0; i < targetObservers.Length; i++)
{
targetObservers[i].OnNext(value);
}
}
internal IObserver<T> Add(IObserver<T> observer)
{
return new ListObserver<T>(_observers.Add(observer));
}
internal IObserver<T> Remove(IObserver<T> observer)
{
var i = Array.IndexOf(_observers.Data, observer);
if (i < 0)
return this;
if (_observers.Data.Length == 2)
{
return _observers.Data[1 - i];
}
else
{
return new ListObserver<T>(_observers.Remove(observer));
}
}
}
public class EmptyObserver<T> : IObserver<T>
{
public static readonly EmptyObserver<T> Instance = new EmptyObserver<T>();
EmptyObserver()
{
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void OnNext(T value)
{
}
}
public class ThrowObserver<T> : IObserver<T>
{
public static readonly ThrowObserver<T> Instance = new ThrowObserver<T>();
ThrowObserver()
{
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
error.Throw();
}
public void OnNext(T value)
{
}
}
public class DisposedObserver<T> : IObserver<T>
{
public static readonly DisposedObserver<T> Instance = new DisposedObserver<T>();
DisposedObserver()
{
}
public void OnCompleted()
{
throw new ObjectDisposedException("");
}
public void OnError(Exception error)
{
throw new ObjectDisposedException("");
}
public void OnNext(T value)
{
throw new ObjectDisposedException("");
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 889dc2f3c5f44d24a98a2c25510b4346
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,170 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace UniRx.InternalUtil
{
/// <summary>
/// Simple supports(only yield return null) lightweight, threadsafe coroutine dispatcher.
/// </summary>
public class MicroCoroutine
{
const int InitialSize = 16;
readonly object runningAndQueueLock = new object();
readonly object arrayLock = new object();
readonly Action<Exception> unhandledExceptionCallback;
int tail = 0;
bool running = false;
IEnumerator[] coroutines = new IEnumerator[InitialSize];
Queue<IEnumerator> waitQueue = new Queue<IEnumerator>();
public MicroCoroutine(Action<Exception> unhandledExceptionCallback)
{
this.unhandledExceptionCallback = unhandledExceptionCallback;
}
public void AddCoroutine(IEnumerator enumerator)
{
lock (runningAndQueueLock)
{
if (running)
{
waitQueue.Enqueue(enumerator);
return;
}
}
// worst case at multi threading, wait lock until finish Run() but it is super rarely.
lock (arrayLock)
{
// Ensure Capacity
if (coroutines.Length == tail)
{
Array.Resize(ref coroutines, checked(tail * 2));
}
coroutines[tail++] = enumerator;
}
}
public void Run()
{
lock (runningAndQueueLock)
{
running = true;
}
lock (arrayLock)
{
var j = tail - 1;
// eliminate array-bound check for i
for (int i = 0; i < coroutines.Length; i++)
{
var coroutine = coroutines[i];
if (coroutine != null)
{
try
{
if (!coroutine.MoveNext())
{
coroutines[i] = null;
}
else
{
#if UNITY_EDITOR
// validation only on Editor.
if (coroutine.Current != null)
{
UnityEngine.Debug.LogWarning("MicroCoroutine supports only yield return null. return value = " + coroutine.Current);
}
#endif
continue; // next i
}
}
catch (Exception ex)
{
coroutines[i] = null;
try
{
unhandledExceptionCallback(ex);
}
catch { }
}
}
// find null, loop from tail
while (i < j)
{
var fromTail = coroutines[j];
if (fromTail != null)
{
try
{
if (!fromTail.MoveNext())
{
coroutines[j] = null;
j--;
continue; // next j
}
else
{
#if UNITY_EDITOR
// validation only on Editor.
if (fromTail.Current != null)
{
UnityEngine.Debug.LogWarning("MicroCoroutine supports only yield return null. return value = " + coroutine.Current);
}
#endif
// swap
coroutines[i] = fromTail;
coroutines[j] = null;
j--;
goto NEXT_LOOP; // next i
}
}
catch (Exception ex)
{
coroutines[j] = null;
j--;
try
{
unhandledExceptionCallback(ex);
}
catch { }
continue; // next j
}
}
else
{
j--;
}
}
tail = i; // loop end
break; // LOOP END
NEXT_LOOP:
continue;
}
lock (runningAndQueueLock)
{
running = false;
while (waitQueue.Count != 0)
{
if (coroutines.Length == tail)
{
Array.Resize(ref coroutines, checked(tail * 2));
}
coroutines[tail++] = waitQueue.Dequeue();
}
}
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 108be6d634275c94a95eeb2a39de0792
timeCreated: 1462599042
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,149 @@
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace UniRx.InternalUtil
{
internal class PriorityQueue<T> where T : IComparable<T>
{
private static long _count = long.MinValue;
private IndexedItem[] _items;
private int _size;
public PriorityQueue()
: this(16)
{
}
public PriorityQueue(int capacity)
{
_items = new IndexedItem[capacity];
_size = 0;
}
private bool IsHigherPriority(int left, int right)
{
return _items[left].CompareTo(_items[right]) < 0;
}
private void Percolate(int index)
{
if (index >= _size || index < 0)
return;
var parent = (index - 1) / 2;
if (parent < 0 || parent == index)
return;
if (IsHigherPriority(index, parent))
{
var temp = _items[index];
_items[index] = _items[parent];
_items[parent] = temp;
Percolate(parent);
}
}
private void Heapify()
{
Heapify(0);
}
private void Heapify(int index)
{
if (index >= _size || index < 0)
return;
var left = 2 * index + 1;
var right = 2 * index + 2;
var first = index;
if (left < _size && IsHigherPriority(left, first))
first = left;
if (right < _size && IsHigherPriority(right, first))
first = right;
if (first != index)
{
var temp = _items[index];
_items[index] = _items[first];
_items[first] = temp;
Heapify(first);
}
}
public int Count { get { return _size; } }
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException("HEAP is Empty");
return _items[0].Value;
}
private void RemoveAt(int index)
{
_items[index] = _items[--_size];
_items[_size] = default(IndexedItem);
Heapify();
if (_size < _items.Length / 4)
{
var temp = _items;
_items = new IndexedItem[_items.Length / 2];
Array.Copy(temp, 0, _items, 0, _size);
}
}
public T Dequeue()
{
var result = Peek();
RemoveAt(0);
return result;
}
public void Enqueue(T item)
{
if (_size >= _items.Length)
{
var temp = _items;
_items = new IndexedItem[_items.Length * 2];
Array.Copy(temp, _items, temp.Length);
}
var index = _size++;
_items[index] = new IndexedItem { Value = item, Id = Interlocked.Increment(ref _count) };
Percolate(index);
}
public bool Remove(T item)
{
for (var i = 0; i < _size; ++i)
{
if (EqualityComparer<T>.Default.Equals(_items[i].Value, item))
{
RemoveAt(i);
return true;
}
}
return false;
}
struct IndexedItem : IComparable<IndexedItem>
{
public T Value;
public long Id;
public int CompareTo(IndexedItem other)
{
var c = Value.CompareTo(other.Value);
if (c == 0)
c = Id.CompareTo(other.Id);
return c;
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7956b408e24dc5a4884fe4f5a3d7c858
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,26 @@
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UniRx.InternalUtil
{
internal static class PromiseHelper
{
internal static void TrySetResultAll<T>(IEnumerable<TaskCompletionSource<T>> source, T value)
{
var rentArray = source.ToArray(); // better to use Arraypool.
var array = rentArray;
var len = rentArray.Length;
for (int i = 0; i < len; i++)
{
array[i].TrySetResult(value);
array[i] = null;
}
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: daa7aa90cece0fe40920a35e79f526dd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,257 @@
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace UniRx.InternalUtil
{
/// <summary>
/// Abstract base class for scheduled work items.
/// </summary>
internal class ScheduledItem : IComparable<ScheduledItem>
{
private readonly BooleanDisposable _disposable = new BooleanDisposable();
private readonly TimeSpan _dueTime;
private readonly Action _action;
/// <summary>
/// Creates a new scheduled work item to run at the specified time.
/// </summary>
/// <param name="dueTime">Absolute time at which the work item has to be executed.</param>
public ScheduledItem(Action action, TimeSpan dueTime)
{
_dueTime = dueTime;
_action = action;
}
/// <summary>
/// Gets the absolute time at which the item is due for invocation.
/// </summary>
public TimeSpan DueTime
{
get { return _dueTime; }
}
/// <summary>
/// Invokes the work item.
/// </summary>
public void Invoke()
{
if (!_disposable.IsDisposed)
{
_action();
}
}
#region Inequality
/// <summary>
/// Compares the work item with another work item based on absolute time values.
/// </summary>
/// <param name="other">Work item to compare the current work item to.</param>
/// <returns>Relative ordering between this and the specified work item.</returns>
/// <remarks>The inequality operators are overloaded to provide results consistent with the IComparable implementation. Equality operators implement traditional reference equality semantics.</remarks>
public int CompareTo(ScheduledItem other)
{
// MSDN: By definition, any object compares greater than null, and two null references compare equal to each other.
if (object.ReferenceEquals(other, null))
return 1;
return DueTime.CompareTo(other.DueTime);
}
/// <summary>
/// Determines whether one specified ScheduledItem&lt;TAbsolute&gt; object is due before a second specified ScheduledItem&lt;TAbsolute&gt; object.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if the DueTime value of left is earlier than the DueTime value of right; otherwise, false.</returns>
/// <remarks>This operator provides results consistent with the IComparable implementation.</remarks>
public static bool operator <(ScheduledItem left, ScheduledItem right)
{
return left.CompareTo(right) < 0;
}
/// <summary>
/// Determines whether one specified ScheduledItem&lt;TAbsolute&gt; object is due before or at the same of a second specified ScheduledItem&lt;TAbsolute&gt; object.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if the DueTime value of left is earlier than or simultaneous with the DueTime value of right; otherwise, false.</returns>
/// <remarks>This operator provides results consistent with the IComparable implementation.</remarks>
public static bool operator <=(ScheduledItem left, ScheduledItem right)
{
return left.CompareTo(right) <= 0;
}
/// <summary>
/// Determines whether one specified ScheduledItem&lt;TAbsolute&gt; object is due after a second specified ScheduledItem&lt;TAbsolute&gt; object.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if the DueTime value of left is later than the DueTime value of right; otherwise, false.</returns>
/// <remarks>This operator provides results consistent with the IComparable implementation.</remarks>
public static bool operator >(ScheduledItem left, ScheduledItem right)
{
return left.CompareTo(right) > 0;
}
/// <summary>
/// Determines whether one specified ScheduledItem&lt;TAbsolute&gt; object is due after or at the same time of a second specified ScheduledItem&lt;TAbsolute&gt; object.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if the DueTime value of left is later than or simultaneous with the DueTime value of right; otherwise, false.</returns>
/// <remarks>This operator provides results consistent with the IComparable implementation.</remarks>
public static bool operator >=(ScheduledItem left, ScheduledItem right)
{
return left.CompareTo(right) >= 0;
}
#endregion
#region Equality
/// <summary>
/// Determines whether two specified ScheduledItem&lt;TAbsolute, TValue&gt; objects are equal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if both ScheduledItem&lt;TAbsolute, TValue&gt; are equal; otherwise, false.</returns>
/// <remarks>This operator does not provide results consistent with the IComparable implementation. Instead, it implements reference equality.</remarks>
public static bool operator ==(ScheduledItem left, ScheduledItem right)
{
return object.ReferenceEquals(left, right);
}
/// <summary>
/// Determines whether two specified ScheduledItem&lt;TAbsolute, TValue&gt; objects are inequal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>true if both ScheduledItem&lt;TAbsolute, TValue&gt; are inequal; otherwise, false.</returns>
/// <remarks>This operator does not provide results consistent with the IComparable implementation. Instead, it implements reference equality.</remarks>
public static bool operator !=(ScheduledItem left, ScheduledItem right)
{
return !(left == right);
}
/// <summary>
/// Determines whether a ScheduledItem&lt;TAbsolute&gt; object is equal to the specified object.
/// </summary>
/// <param name="obj">The object to compare to the current ScheduledItem&lt;TAbsolute&gt; object.</param>
/// <returns>true if the obj parameter is a ScheduledItem&lt;TAbsolute&gt; object and is equal to the current ScheduledItem&lt;TAbsolute&gt; object; otherwise, false.</returns>
public override bool Equals(object obj)
{
return object.ReferenceEquals(this, obj);
}
/// <summary>
/// Returns the hash code for the current ScheduledItem&lt;TAbsolute&gt; object.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
public IDisposable Cancellation
{
get
{
return _disposable;
}
}
/// <summary>
/// Gets whether the work item has received a cancellation request.
/// </summary>
public bool IsCanceled
{
get { return _disposable.IsDisposed; }
}
}
/// <summary>
/// Efficient scheduler queue that maintains scheduled items sorted by absolute time.
/// </summary>
/// <remarks>This type is not thread safe; users should ensure proper synchronization.</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "But it *is* a queue!")]
internal class SchedulerQueue
{
private readonly PriorityQueue<ScheduledItem> _queue;
/// <summary>
/// Creates a new scheduler queue with a default initial capacity.
/// </summary>
public SchedulerQueue()
: this(1024)
{
}
/// <summary>
/// Creats a new scheduler queue with the specified initial capacity.
/// </summary>
/// <param name="capacity">Initial capacity of the scheduler queue.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than zero.</exception>
public SchedulerQueue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
_queue = new PriorityQueue<ScheduledItem>(capacity);
}
/// <summary>
/// Gets the number of scheduled items in the scheduler queue.
/// </summary>
public int Count
{
get
{
return _queue.Count;
}
}
/// <summary>
/// Enqueues the specified work item to be scheduled.
/// </summary>
/// <param name="scheduledItem">Work item to be scheduled.</param>
public void Enqueue(ScheduledItem scheduledItem)
{
_queue.Enqueue(scheduledItem);
}
/// <summary>
/// Removes the specified work item from the scheduler queue.
/// </summary>
/// <param name="scheduledItem">Work item to be removed from the scheduler queue.</param>
/// <returns>true if the item was found; false otherwise.</returns>
public bool Remove(ScheduledItem scheduledItem)
{
return _queue.Remove(scheduledItem);
}
/// <summary>
/// Dequeues the next work item from the scheduler queue.
/// </summary>
/// <returns>Next work item in the scheduler queue (removed).</returns>
public ScheduledItem Dequeue()
{
return _queue.Dequeue();
}
/// <summary>
/// Peeks the next work item in the scheduler queue.
/// </summary>
/// <returns>Next work item in the scheduler queue (not removed).</returns>
public ScheduledItem Peek()
{
return _queue.Peek();
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 45457ee4a77967347828238b7a52b851
timeCreated: 1455373898
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,112 @@
using System;
namespace UniRx.InternalUtil
{
public class ThreadSafeQueueWorker
{
const int MaxArrayLength = 0X7FEFFFFF;
const int InitialSize = 16;
object gate = new object();
bool dequing = false;
int actionListCount = 0;
Action<object>[] actionList = new Action<object>[InitialSize];
object[] actionStates = new object[InitialSize];
int waitingListCount = 0;
Action<object>[] waitingList = new Action<object>[InitialSize];
object[] waitingStates = new object[InitialSize];
public void Enqueue(Action<object> action, object state)
{
lock (gate)
{
if (dequing)
{
// Ensure Capacity
if (waitingList.Length == waitingListCount)
{
var newLength = waitingListCount * 2;
if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength;
var newArray = new Action<object>[newLength];
var newArrayState = new object[newLength];
Array.Copy(waitingList, newArray, waitingListCount);
Array.Copy(waitingStates, newArrayState, waitingListCount);
waitingList = newArray;
waitingStates = newArrayState;
}
waitingList[waitingListCount] = action;
waitingStates[waitingListCount] = state;
waitingListCount++;
}
else
{
// Ensure Capacity
if (actionList.Length == actionListCount)
{
var newLength = actionListCount * 2;
if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength;
var newArray = new Action<object>[newLength];
var newArrayState = new object[newLength];
Array.Copy(actionList, newArray, actionListCount);
Array.Copy(actionStates, newArrayState, actionListCount);
actionList = newArray;
actionStates = newArrayState;
}
actionList[actionListCount] = action;
actionStates[actionListCount] = state;
actionListCount++;
}
}
}
public void ExecuteAll(Action<Exception> unhandledExceptionCallback)
{
lock (gate)
{
if (actionListCount == 0) return;
dequing = true;
}
for (int i = 0; i < actionListCount; i++)
{
var action = actionList[i];
var state = actionStates[i];
try
{
action(state);
}
catch (Exception ex)
{
unhandledExceptionCallback(ex);
}
finally
{
// Clear
actionList[i] = null;
actionStates[i] = null;
}
}
lock (gate)
{
dequing = false;
var swapTempActionList = actionList;
var swapTempActionStates = actionStates;
actionListCount = waitingListCount;
actionList = waitingList;
actionStates = waitingStates;
waitingListCount = 0;
waitingList = swapTempActionList;
waitingStates = swapTempActionStates;
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 768cbfcbe2a8e704a8953eea28cd33df
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,271 @@
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6))
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UniRx.InternalUtil
{
internal static class UnityEqualityComparer
{
public static readonly IEqualityComparer<Vector2> Vector2 = new Vector2EqualityComparer();
public static readonly IEqualityComparer<Vector3> Vector3 = new Vector3EqualityComparer();
public static readonly IEqualityComparer<Vector4> Vector4 = new Vector4EqualityComparer();
public static readonly IEqualityComparer<Color> Color = new ColorEqualityComparer();
public static readonly IEqualityComparer<Color32> Color32 = new Color32EqualityComparer();
public static readonly IEqualityComparer<Rect> Rect = new RectEqualityComparer();
public static readonly IEqualityComparer<Bounds> Bounds = new BoundsEqualityComparer();
public static readonly IEqualityComparer<Quaternion> Quaternion = new QuaternionEqualityComparer();
static readonly RuntimeTypeHandle vector2Type = typeof(Vector2).TypeHandle;
static readonly RuntimeTypeHandle vector3Type = typeof(Vector3).TypeHandle;
static readonly RuntimeTypeHandle vector4Type = typeof(Vector4).TypeHandle;
static readonly RuntimeTypeHandle colorType = typeof(Color).TypeHandle;
static readonly RuntimeTypeHandle color32Type = typeof(Color32).TypeHandle;
static readonly RuntimeTypeHandle rectType = typeof(Rect).TypeHandle;
static readonly RuntimeTypeHandle boundsType = typeof(Bounds).TypeHandle;
static readonly RuntimeTypeHandle quaternionType = typeof(Quaternion).TypeHandle;
#if UNITY_2017_2_OR_NEWER
public static readonly IEqualityComparer<Vector2Int> Vector2Int = new Vector2IntEqualityComparer();
public static readonly IEqualityComparer<Vector3Int> Vector3Int = new Vector3IntEqualityComparer();
public static readonly IEqualityComparer<RangeInt> RangeInt = new RangeIntEqualityComparer();
public static readonly IEqualityComparer<RectInt> RectInt = new RectIntEqualityComparer();
public static readonly IEqualityComparer<BoundsInt> BoundsInt = new BoundsIntEqualityComparer();
static readonly RuntimeTypeHandle vector2IntType = typeof(Vector2Int).TypeHandle;
static readonly RuntimeTypeHandle vector3IntType = typeof(Vector3Int).TypeHandle;
static readonly RuntimeTypeHandle rangeIntType = typeof(RangeInt).TypeHandle;
static readonly RuntimeTypeHandle rectIntType = typeof(RectInt).TypeHandle;
static readonly RuntimeTypeHandle boundsIntType = typeof(BoundsInt).TypeHandle;
#endif
static class Cache<T>
{
public static readonly IEqualityComparer<T> Comparer;
static Cache()
{
var comparer = GetDefaultHelper(typeof(T));
if (comparer == null)
{
Comparer = EqualityComparer<T>.Default;
}
else
{
Comparer = (IEqualityComparer<T>)comparer;
}
}
}
public static IEqualityComparer<T> GetDefault<T>()
{
return Cache<T>.Comparer;
}
static object GetDefaultHelper(Type type)
{
var t = type.TypeHandle;
if (t.Equals(vector2Type)) return (object)UnityEqualityComparer.Vector2;
if (t.Equals(vector3Type)) return (object)UnityEqualityComparer.Vector3;
if (t.Equals(vector4Type)) return (object)UnityEqualityComparer.Vector4;
if (t.Equals(colorType)) return (object)UnityEqualityComparer.Color;
if (t.Equals(color32Type)) return (object)UnityEqualityComparer.Color32;
if (t.Equals(rectType)) return (object)UnityEqualityComparer.Rect;
if (t.Equals(boundsType)) return (object)UnityEqualityComparer.Bounds;
if (t.Equals(quaternionType)) return (object)UnityEqualityComparer.Quaternion;
#if UNITY_2017_2_OR_NEWER
if (t.Equals(vector2IntType)) return (object)UnityEqualityComparer.Vector2Int;
if (t.Equals(vector3IntType)) return (object)UnityEqualityComparer.Vector3Int;
if (t.Equals(rangeIntType)) return (object)UnityEqualityComparer.RangeInt;
if (t.Equals(rectIntType)) return (object)UnityEqualityComparer.RectInt;
if (t.Equals(boundsIntType)) return (object)UnityEqualityComparer.BoundsInt;
#endif
return null;
}
sealed class Vector2EqualityComparer : IEqualityComparer<Vector2>
{
public bool Equals(Vector2 self, Vector2 vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y);
}
public int GetHashCode(Vector2 obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2;
}
}
sealed class Vector3EqualityComparer : IEqualityComparer<Vector3>
{
public bool Equals(Vector3 self, Vector3 vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z);
}
public int GetHashCode(Vector3 obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2;
}
}
sealed class Vector4EqualityComparer : IEqualityComparer<Vector4>
{
public bool Equals(Vector4 self, Vector4 vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z) && self.w.Equals(vector.w);
}
public int GetHashCode(Vector4 obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2 ^ obj.w.GetHashCode() >> 1;
}
}
sealed class ColorEqualityComparer : IEqualityComparer<Color>
{
public bool Equals(Color self, Color other)
{
return self.r.Equals(other.r) && self.g.Equals(other.g) && self.b.Equals(other.b) && self.a.Equals(other.a);
}
public int GetHashCode(Color obj)
{
return obj.r.GetHashCode() ^ obj.g.GetHashCode() << 2 ^ obj.b.GetHashCode() >> 2 ^ obj.a.GetHashCode() >> 1;
}
}
sealed class RectEqualityComparer : IEqualityComparer<Rect>
{
public bool Equals(Rect self, Rect other)
{
return self.x.Equals(other.x) && self.width.Equals(other.width) && self.y.Equals(other.y) && self.height.Equals(other.height);
}
public int GetHashCode(Rect obj)
{
return obj.x.GetHashCode() ^ obj.width.GetHashCode() << 2 ^ obj.y.GetHashCode() >> 2 ^ obj.height.GetHashCode() >> 1;
}
}
sealed class BoundsEqualityComparer : IEqualityComparer<Bounds>
{
public bool Equals(Bounds self, Bounds vector)
{
return self.center.Equals(vector.center) && self.extents.Equals(vector.extents);
}
public int GetHashCode(Bounds obj)
{
return obj.center.GetHashCode() ^ obj.extents.GetHashCode() << 2;
}
}
sealed class QuaternionEqualityComparer : IEqualityComparer<Quaternion>
{
public bool Equals(Quaternion self, Quaternion vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z) && self.w.Equals(vector.w);
}
public int GetHashCode(Quaternion obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2 ^ obj.w.GetHashCode() >> 1;
}
}
sealed class Color32EqualityComparer : IEqualityComparer<Color32>
{
public bool Equals(Color32 self, Color32 vector)
{
return self.a.Equals(vector.a) && self.r.Equals(vector.r) && self.g.Equals(vector.g) && self.b.Equals(vector.b);
}
public int GetHashCode(Color32 obj)
{
return obj.a.GetHashCode() ^ obj.r.GetHashCode() << 2 ^ obj.g.GetHashCode() >> 2 ^ obj.b.GetHashCode() >> 1;
}
}
#if UNITY_2017_2_OR_NEWER
sealed class Vector2IntEqualityComparer : IEqualityComparer<Vector2Int>
{
public bool Equals(Vector2Int self, Vector2Int vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y);
}
public int GetHashCode(Vector2Int obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2;
}
}
sealed class Vector3IntEqualityComparer : IEqualityComparer<Vector3Int>
{
public static readonly Vector3IntEqualityComparer Default = new Vector3IntEqualityComparer();
public bool Equals(Vector3Int self, Vector3Int vector)
{
return self.x.Equals(vector.x) && self.y.Equals(vector.y) && self.z.Equals(vector.z);
}
public int GetHashCode(Vector3Int obj)
{
return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2 ^ obj.z.GetHashCode() >> 2;
}
}
sealed class RangeIntEqualityComparer : IEqualityComparer<RangeInt>
{
public bool Equals(RangeInt self, RangeInt vector)
{
return self.start.Equals(vector.start) && self.length.Equals(vector.length);
}
public int GetHashCode(RangeInt obj)
{
return obj.start.GetHashCode() ^ obj.length.GetHashCode() << 2;
}
}
sealed class RectIntEqualityComparer : IEqualityComparer<RectInt>
{
public bool Equals(RectInt self, RectInt other)
{
return self.x.Equals(other.x) && self.width.Equals(other.width) && self.y.Equals(other.y) && self.height.Equals(other.height);
}
public int GetHashCode(RectInt obj)
{
return obj.x.GetHashCode() ^ obj.width.GetHashCode() << 2 ^ obj.y.GetHashCode() >> 2 ^ obj.height.GetHashCode() >> 1;
}
}
sealed class BoundsIntEqualityComparer : IEqualityComparer<BoundsInt>
{
public bool Equals(BoundsInt self, BoundsInt vector)
{
return Vector3IntEqualityComparer.Default.Equals(self.position, vector.position)
&& Vector3IntEqualityComparer.Default.Equals(self.size, vector.size);
}
public int GetHashCode(BoundsInt obj)
{
return Vector3IntEqualityComparer.Default.GetHashCode(obj.position) ^ Vector3IntEqualityComparer.Default.GetHashCode(obj.size) << 2;
}
}
#endif
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 626a410137515ac45bb59d1ca91d8f3f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,678 @@
// original code from rx.codeplex.com
// some modified.
/* ------------------ */
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System;
using UniRx.InternalUtil;
#pragma warning disable 0659
#pragma warning disable 0661
namespace UniRx
{
/// <summary>
/// Provides a mechanism for receiving push-based notifications and returning a response.
/// </summary>
/// <typeparam name="TValue">
/// The type of the elements received by the observer.
/// This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the result returned from the observer's notification handlers.
/// This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
/// </typeparam>
public interface IObserver<TValue, TResult>
{
/// <summary>
/// Notifies the observer of a new element in the sequence.
/// </summary>
/// <param name="value">The new element in the sequence.</param>
/// <returns>Result returned upon observation of a new element.</returns>
TResult OnNext(TValue value);
/// <summary>
/// Notifies the observer that an exception has occurred.
/// </summary>
/// <param name="exception">The exception that occurred.</param>
/// <returns>Result returned upon observation of an error.</returns>
TResult OnError(Exception exception);
/// <summary>
/// Notifies the observer of the end of the sequence.
/// </summary>
/// <returns>Result returned upon observation of the sequence completion.</returns>
TResult OnCompleted();
}
/// <summary>
/// Indicates the type of a notification.
/// </summary>
public enum NotificationKind
{
/// <summary>
/// Represents an OnNext notification.
/// </summary>
OnNext,
/// <summary>
/// Represents an OnError notification.
/// </summary>
OnError,
/// <summary>
/// Represents an OnCompleted notification.
/// </summary>
OnCompleted
}
/// <summary>
/// Represents a notification to an observer.
/// </summary>
/// <typeparam name="T">The type of the elements received by the observer.</typeparam>
[Serializable]
public abstract class Notification<T> : IEquatable<Notification<T>>
{
/// <summary>
/// Default constructor used by derived types.
/// </summary>
protected internal Notification()
{
}
/// <summary>
/// Returns the value of an OnNext notification or throws an exception.
/// </summary>
public abstract T Value
{
get;
}
/// <summary>
/// Returns a value that indicates whether the notification has a value.
/// </summary>
public abstract bool HasValue
{
get;
}
/// <summary>
/// Returns the exception of an OnError notification or returns null.
/// </summary>
public abstract Exception Exception
{
get;
}
/// <summary>
/// Gets the kind of notification that is represented.
/// </summary>
public abstract NotificationKind Kind
{
get;
}
/// <summary>
/// Represents an OnNext notification to an observer.
/// </summary>
[DebuggerDisplay("OnNext({Value})")]
[Serializable]
internal sealed class OnNextNotification : Notification<T>
{
T value;
/// <summary>
/// Constructs a notification of a new value.
/// </summary>
public OnNextNotification(T value)
{
this.value = value;
}
/// <summary>
/// Returns the value of an OnNext notification.
/// </summary>
public override T Value { get { return value; } }
/// <summary>
/// Returns null.
/// </summary>
public override Exception Exception { get { return null; } }
/// <summary>
/// Returns true.
/// </summary>
public override bool HasValue { get { return true; } }
/// <summary>
/// Returns NotificationKind.OnNext.
/// </summary>
public override NotificationKind Kind { get { return NotificationKind.OnNext; } }
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return EqualityComparer<T>.Default.GetHashCode(Value);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
public override bool Equals(Notification<T> other)
{
if (Object.ReferenceEquals(this, other))
return true;
if (Object.ReferenceEquals(other, null))
return false;
if (other.Kind != NotificationKind.OnNext)
return false;
return EqualityComparer<T>.Default.Equals(Value, other.Value);
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "OnNext({0})", Value);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public override void Accept(IObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
observer.OnNext(Value);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(IObserver<T, TResult> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
return observer.OnNext(Value);
}
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
onNext(Value);
}
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
return onNext(Value);
}
}
/// <summary>
/// Represents an OnError notification to an observer.
/// </summary>
#if !NO_DEBUGGER_ATTRIBUTES
[DebuggerDisplay("OnError({Exception})")]
#endif
#if !NO_SERIALIZABLE
[Serializable]
#endif
internal sealed class OnErrorNotification : Notification<T>
{
Exception exception;
/// <summary>
/// Constructs a notification of an exception.
/// </summary>
public OnErrorNotification(Exception exception)
{
this.exception = exception;
}
/// <summary>
/// Throws the exception.
/// </summary>
public override T Value { get { exception.Throw(); throw exception; } }
/// <summary>
/// Returns the exception.
/// </summary>
public override Exception Exception { get { return exception; } }
/// <summary>
/// Returns false.
/// </summary>
public override bool HasValue { get { return false; } }
/// <summary>
/// Returns NotificationKind.OnError.
/// </summary>
public override NotificationKind Kind { get { return NotificationKind.OnError; } }
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return Exception.GetHashCode();
}
/// <summary>
/// Indicates whether this instance and other are equal.
/// </summary>
public override bool Equals(Notification<T> other)
{
if (Object.ReferenceEquals(this, other))
return true;
if (Object.ReferenceEquals(other, null))
return false;
if (other.Kind != NotificationKind.OnError)
return false;
return Object.Equals(Exception, other.Exception);
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "OnError({0})", Exception.GetType().FullName);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public override void Accept(IObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
observer.OnError(Exception);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(IObserver<T, TResult> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
return observer.OnError(Exception);
}
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
onError(Exception);
}
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
return onError(Exception);
}
}
/// <summary>
/// Represents an OnCompleted notification to an observer.
/// </summary>
[DebuggerDisplay("OnCompleted()")]
[Serializable]
internal sealed class OnCompletedNotification : Notification<T>
{
/// <summary>
/// Constructs a notification of the end of a sequence.
/// </summary>
public OnCompletedNotification()
{
}
/// <summary>
/// Throws an InvalidOperationException.
/// </summary>
public override T Value { get { throw new InvalidOperationException("No Value"); } }
/// <summary>
/// Returns null.
/// </summary>
public override Exception Exception { get { return null; } }
/// <summary>
/// Returns false.
/// </summary>
public override bool HasValue { get { return false; } }
/// <summary>
/// Returns NotificationKind.OnCompleted.
/// </summary>
public override NotificationKind Kind { get { return NotificationKind.OnCompleted; } }
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return typeof(T).GetHashCode() ^ 8510;
}
/// <summary>
/// Indicates whether this instance and other are equal.
/// </summary>
public override bool Equals(Notification<T> other)
{
if (Object.ReferenceEquals(this, other))
return true;
if (Object.ReferenceEquals(other, null))
return false;
return other.Kind == NotificationKind.OnCompleted;
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
public override string ToString()
{
return "OnCompleted()";
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public override void Accept(IObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
observer.OnCompleted();
}
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(IObserver<T, TResult> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
return observer.OnCompleted();
}
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
onCompleted();
}
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
return onCompleted();
}
}
/// <summary>
/// Determines whether the current Notification&lt;T&gt; object has the same observer message payload as a specified Notification&lt;T&gt; value.
/// </summary>
/// <param name="other">An object to compare to the current Notification&lt;T&gt; object.</param>
/// <returns>true if both Notification&lt;T&gt; objects have the same observer message payload; otherwise, false.</returns>
/// <remarks>
/// Equality of Notification&lt;T&gt; objects is based on the equality of the observer message payload they represent, including the notification Kind and the Value or Exception (if any).
/// This means two Notification&lt;T&gt; objects can be equal even though they don't represent the same observer method call, but have the same Kind and have equal parameters passed to the observer method.
/// In case one wants to determine whether two Notification&lt;T&gt; objects represent the same observer method call, use Object.ReferenceEquals identity equality instead.
/// </remarks>
public abstract bool Equals(Notification<T> other);
/// <summary>
/// Determines whether the two specified Notification&lt;T&gt; objects have the same observer message payload.
/// </summary>
/// <param name="left">The first Notification&lt;T&gt; to compare, or null.</param>
/// <param name="right">The second Notification&lt;T&gt; to compare, or null.</param>
/// <returns>true if the first Notification&lt;T&gt; value has the same observer message payload as the second Notification&lt;T&gt; value; otherwise, false.</returns>
/// <remarks>
/// Equality of Notification&lt;T&gt; objects is based on the equality of the observer message payload they represent, including the notification Kind and the Value or Exception (if any).
/// This means two Notification&lt;T&gt; objects can be equal even though they don't represent the same observer method call, but have the same Kind and have equal parameters passed to the observer method.
/// In case one wants to determine whether two Notification&lt;T&gt; objects represent the same observer method call, use Object.ReferenceEquals identity equality instead.
/// </remarks>
public static bool operator ==(Notification<T> left, Notification<T> right)
{
if (object.ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null)
return false;
return left.Equals(right);
}
/// <summary>
/// Determines whether the two specified Notification&lt;T&gt; objects have a different observer message payload.
/// </summary>
/// <param name="left">The first Notification&lt;T&gt; to compare, or null.</param>
/// <param name="right">The second Notification&lt;T&gt; to compare, or null.</param>
/// <returns>true if the first Notification&lt;T&gt; value has a different observer message payload as the second Notification&lt;T&gt; value; otherwise, false.</returns>
/// <remarks>
/// Equality of Notification&lt;T&gt; objects is based on the equality of the observer message payload they represent, including the notification Kind and the Value or Exception (if any).
/// This means two Notification&lt;T&gt; objects can be equal even though they don't represent the same observer method call, but have the same Kind and have equal parameters passed to the observer method.
/// In case one wants to determine whether two Notification&lt;T&gt; objects represent a different observer method call, use Object.ReferenceEquals identity equality instead.
/// </remarks>
public static bool operator !=(Notification<T> left, Notification<T> right)
{
return !(left == right);
}
/// <summary>
/// Determines whether the specified System.Object is equal to the current Notification&lt;T&gt;.
/// </summary>
/// <param name="obj">The System.Object to compare with the current Notification&lt;T&gt;.</param>
/// <returns>true if the specified System.Object is equal to the current Notification&lt;T&gt;; otherwise, false.</returns>
/// <remarks>
/// Equality of Notification&lt;T&gt; objects is based on the equality of the observer message payload they represent, including the notification Kind and the Value or Exception (if any).
/// This means two Notification&lt;T&gt; objects can be equal even though they don't represent the same observer method call, but have the same Kind and have equal parameters passed to the observer method.
/// In case one wants to determine whether two Notification&lt;T&gt; objects represent the same observer method call, use Object.ReferenceEquals identity equality instead.
/// </remarks>
public override bool Equals(object obj)
{
return Equals(obj as Notification<T>);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public abstract void Accept(IObserver<T> observer);
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <typeparam name="TResult">The type of the result returned from the observer's notification handlers.</typeparam>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public abstract TResult Accept<TResult>(IObserver<T, TResult> observer);
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public abstract void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted);
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <typeparam name="TResult">The type of the result returned from the notification handler delegates.</typeparam>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public abstract TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted);
/// <summary>
/// Returns an observable sequence with a single notification, using the immediate scheduler.
/// </summary>
/// <returns>The observable sequence that surfaces the behavior of the notification upon subscription.</returns>
public IObservable<T> ToObservable()
{
return this.ToObservable(Scheduler.Immediate);
}
/// <summary>
/// Returns an observable sequence with a single notification.
/// </summary>
/// <param name="scheduler">Scheduler to send out the notification calls on.</param>
/// <returns>The observable sequence that surfaces the behavior of the notification upon subscription.</returns>
public IObservable<T> ToObservable(IScheduler scheduler)
{
if (scheduler == null)
throw new ArgumentNullException("scheduler");
return Observable.Create<T>(observer => scheduler.Schedule(() =>
{
this.Accept(observer);
if (this.Kind == NotificationKind.OnNext)
observer.OnCompleted();
}));
}
}
/// <summary>
/// Provides a set of static methods for constructing notifications.
/// </summary>
public static class Notification
{
/// <summary>
/// Creates an object that represents an OnNext notification to an observer.
/// </summary>
/// <typeparam name="T">The type of the elements received by the observer. Upon dematerialization of the notifications into an observable sequence, this type is used as the element type for the sequence.</typeparam>
/// <param name="value">The value contained in the notification.</param>
/// <returns>The OnNext notification containing the value.</returns>
public static Notification<T> CreateOnNext<T>(T value)
{
return new Notification<T>.OnNextNotification(value);
}
/// <summary>
/// Creates an object that represents an OnError notification to an observer.
/// </summary>
/// <typeparam name="T">The type of the elements received by the observer. Upon dematerialization of the notifications into an observable sequence, this type is used as the element type for the sequence.</typeparam>
/// <param name="error">The exception contained in the notification.</param>
/// <returns>The OnError notification containing the exception.</returns>
/// <exception cref="ArgumentNullException"><paramref name="error"/> is null.</exception>
public static Notification<T> CreateOnError<T>(Exception error)
{
if (error == null)
throw new ArgumentNullException("error");
return new Notification<T>.OnErrorNotification(error);
}
/// <summary>
/// Creates an object that represents an OnCompleted notification to an observer.
/// </summary>
/// <typeparam name="T">The type of the elements received by the observer. Upon dematerialization of the notifications into an observable sequence, this type is used as the element type for the sequence.</typeparam>
/// <returns>The OnCompleted notification.</returns>
public static Notification<T> CreateOnCompleted<T>()
{
return new Notification<T>.OnCompletedNotification();
}
}
}
#pragma warning restore 0659
#pragma warning restore 0661

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 169d02559aa6b3e459fbae10f2acecd8
timeCreated: 1455373897
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7c4c0b009d4f74543b3a334abc45323a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UniRx
{
/// <summary>
/// Notify boolean flag.
/// </summary>
public class BooleanNotifier : IObservable<bool>
{
readonly Subject<bool> boolTrigger = new Subject<bool>();
bool boolValue;
/// <summary>Current flag value</summary>
public bool Value
{
get { return boolValue; }
set
{
boolValue = value;
boolTrigger.OnNext(value);
}
}
/// <summary>
/// Setup initial flag.
/// </summary>
public BooleanNotifier(bool initialValue = false)
{
this.Value = initialValue;
}
/// <summary>
/// Set and raise true if current value isn't true.
/// </summary>
public void TurnOn()
{
if (Value != true)
{
Value = true;
}
}
/// <summary>
/// Set and raise false if current value isn't false.
/// </summary>
public void TurnOff()
{
if (Value != false)
{
Value = false;
}
}
/// <summary>
/// Set and raise reverse value.
/// </summary>
public void SwitchValue()
{
Value = !Value;
}
/// <summary>
/// Subscribe observer.
/// </summary>
public IDisposable Subscribe(IObserver<bool> observer)
{
return boolTrigger.Subscribe(observer);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5ee30c0abdddd7241acbe24df0637678
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UniRx
{
/// <summary>Event kind of CountNotifier.</summary>
public enum CountChangedStatus
{
/// <summary>Count incremented.</summary>
Increment,
/// <summary>Count decremented.</summary>
Decrement,
/// <summary>Count is zero.</summary>
Empty,
/// <summary>Count arrived max.</summary>
Max
}
/// <summary>
/// Notify event of count flag.
/// </summary>
public class CountNotifier : IObservable<CountChangedStatus>
{
readonly object lockObject = new object();
readonly Subject<CountChangedStatus> statusChanged = new Subject<CountChangedStatus>();
readonly int max;
public int Max { get { return max; } }
public int Count { get; private set; }
/// <summary>
/// Setup max count of signal.
/// </summary>
public CountNotifier(int max = int.MaxValue)
{
if (max <= 0)
{
throw new ArgumentException("max");
}
this.max = max;
}
/// <summary>
/// Increment count and notify status.
/// </summary>
public IDisposable Increment(int incrementCount = 1)
{
if (incrementCount < 0)
{
throw new ArgumentException("incrementCount");
}
lock (lockObject)
{
if (Count == Max) return Disposable.Empty;
else if (incrementCount + Count > Max) Count = Max;
else Count += incrementCount;
statusChanged.OnNext(CountChangedStatus.Increment);
if (Count == Max) statusChanged.OnNext(CountChangedStatus.Max);
return Disposable.Create(() => this.Decrement(incrementCount));
}
}
/// <summary>
/// Decrement count and notify status.
/// </summary>
public void Decrement(int decrementCount = 1)
{
if (decrementCount < 0)
{
throw new ArgumentException("decrementCount");
}
lock (lockObject)
{
if (Count == 0) return;
else if (Count - decrementCount < 0) Count = 0;
else Count -= decrementCount;
statusChanged.OnNext(CountChangedStatus.Decrement);
if (Count == 0) statusChanged.OnNext(CountChangedStatus.Empty);
}
}
/// <summary>
/// Subscribe observer.
/// </summary>
public IDisposable Subscribe(IObserver<CountChangedStatus> observer)
{
return statusChanged.Subscribe(observer);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 503af1c1dc279164e83011be5110633e
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,209 @@
using System;
using System.Collections.Generic;
using UniRx.InternalUtil;
namespace UniRx
{
public interface IMessagePublisher
{
/// <summary>
/// Send Message to all receiver.
/// </summary>
void Publish<T>(T message);
}
public interface IMessageReceiver
{
/// <summary>
/// Subscribe typed message.
/// </summary>
IObservable<T> Receive<T>();
}
public interface IMessageBroker : IMessagePublisher, IMessageReceiver
{
}
public interface IAsyncMessagePublisher
{
/// <summary>
/// Send Message to all receiver and await complete.
/// </summary>
IObservable<Unit> PublishAsync<T>(T message);
}
public interface IAsyncMessageReceiver
{
/// <summary>
/// Subscribe typed message.
/// </summary>
IDisposable Subscribe<T>(Func<T, IObservable<Unit>> asyncMessageReceiver);
}
public interface IAsyncMessageBroker : IAsyncMessagePublisher, IAsyncMessageReceiver
{
}
/// <summary>
/// In-Memory PubSub filtered by Type.
/// </summary>
public class MessageBroker : IMessageBroker, IDisposable
{
/// <summary>
/// MessageBroker in Global scope.
/// </summary>
public static readonly IMessageBroker Default = new MessageBroker();
bool isDisposed = false;
readonly Dictionary<Type, object> notifiers = new Dictionary<Type, object>();
public void Publish<T>(T message)
{
object notifier;
lock (notifiers)
{
if (isDisposed) return;
if (!notifiers.TryGetValue(typeof(T), out notifier))
{
return;
}
}
((ISubject<T>)notifier).OnNext(message);
}
public IObservable<T> Receive<T>()
{
object notifier;
lock (notifiers)
{
if (isDisposed) throw new ObjectDisposedException("MessageBroker");
if (!notifiers.TryGetValue(typeof(T), out notifier))
{
ISubject<T> n = new Subject<T>().Synchronize();
notifier = n;
notifiers.Add(typeof(T), notifier);
}
}
return ((IObservable<T>)notifier).AsObservable();
}
public void Dispose()
{
lock (notifiers)
{
if (!isDisposed)
{
isDisposed = true;
notifiers.Clear();
}
}
}
}
/// <summary>
/// In-Memory PubSub filtered by Type.
/// </summary>
public class AsyncMessageBroker : IAsyncMessageBroker, IDisposable
{
/// <summary>
/// AsyncMessageBroker in Global scope.
/// </summary>
public static readonly IAsyncMessageBroker Default = new AsyncMessageBroker();
bool isDisposed = false;
readonly Dictionary<Type, object> notifiers = new Dictionary<Type, object>();
public IObservable<Unit> PublishAsync<T>(T message)
{
UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>> notifier;
lock (notifiers)
{
if (isDisposed) throw new ObjectDisposedException("AsyncMessageBroker");
object _notifier;
if (notifiers.TryGetValue(typeof(T), out _notifier))
{
notifier = (UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>>)_notifier;
}
else
{
return Observable.ReturnUnit();
}
}
var data = notifier.Data;
var awaiter = new IObservable<Unit>[data.Length];
for (int i = 0; i < data.Length; i++)
{
awaiter[i] = data[i].Invoke(message);
}
return Observable.WhenAll(awaiter);
}
public IDisposable Subscribe<T>(Func<T, IObservable<Unit>> asyncMessageReceiver)
{
lock (notifiers)
{
if (isDisposed) throw new ObjectDisposedException("AsyncMessageBroker");
object _notifier;
if (!notifiers.TryGetValue(typeof(T), out _notifier))
{
var notifier = UniRx.InternalUtil.ImmutableList<Func<T, IObservable<Unit>>>.Empty;
notifier = notifier.Add(asyncMessageReceiver);
notifiers.Add(typeof(T), notifier);
}
else
{
var notifier = (ImmutableList<Func<T, IObservable<Unit>>>)_notifier;
notifier = notifier.Add(asyncMessageReceiver);
notifiers[typeof(T)] = notifier;
}
}
return new Subscription<T>(this, asyncMessageReceiver);
}
public void Dispose()
{
lock (notifiers)
{
if (!isDisposed)
{
isDisposed = true;
notifiers.Clear();
}
}
}
class Subscription<T> : IDisposable
{
readonly AsyncMessageBroker parent;
readonly Func<T, IObservable<Unit>> asyncMessageReceiver;
public Subscription(AsyncMessageBroker parent, Func<T, IObservable<Unit>> asyncMessageReceiver)
{
this.parent = parent;
this.asyncMessageReceiver = asyncMessageReceiver;
}
public void Dispose()
{
lock (parent.notifiers)
{
object _notifier;
if (parent.notifiers.TryGetValue(typeof(T), out _notifier))
{
var notifier = (ImmutableList<Func<T, IObservable<Unit>>>)_notifier;
notifier = notifier.Remove(asyncMessageReceiver);
parent.notifiers[typeof(T)] = notifier;
}
}
}
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 9dc5e3c48d083d4418ab67287f050267
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,72 @@
using System;
namespace UniRx
{
/// <summary>
/// Notify value on setuped scheduler.
/// </summary>
public class ScheduledNotifier<T> : IObservable<T>, IProgress<T>
{
readonly IScheduler scheduler;
readonly Subject<T> trigger = new Subject<T>();
/// <summary>
/// Use scheduler is Scheduler.DefaultSchedulers.ConstantTimeOperations.
/// </summary>
public ScheduledNotifier()
{
this.scheduler = Scheduler.DefaultSchedulers.ConstantTimeOperations;
}
/// <summary>
/// Use scheduler is argument's scheduler.
/// </summary>
public ScheduledNotifier(IScheduler scheduler)
{
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
this.scheduler = scheduler;
}
/// <summary>
/// Push value to subscribers on setuped scheduler.
/// </summary>
public void Report(T value)
{
scheduler.Schedule(() => trigger.OnNext(value));
}
/// <summary>
/// Push value to subscribers on setuped scheduler.
/// </summary>
public IDisposable Report(T value, TimeSpan dueTime)
{
var cancel = scheduler.Schedule(dueTime, () => trigger.OnNext(value));
return cancel;
}
/// <summary>
/// Push value to subscribers on setuped scheduler.
/// </summary>
public IDisposable Report(T value, DateTimeOffset dueTime)
{
var cancel = scheduler.Schedule(dueTime, () => trigger.OnNext(value));
return cancel;
}
/// <summary>
/// Subscribe observer.
/// </summary>
public IDisposable Subscribe(IObserver<T> observer)
{
if (observer == null)
{
throw new ArgumentNullException("observer");
}
return trigger.Subscribe(observer);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e6f53242e655cbe4e889538216dc9e17
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Text;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IObservable<TSource> Scan<TSource>(this IObservable<TSource> source, Func<TSource, TSource, TSource> accumulator)
{
return new ScanObservable<TSource>(source, accumulator);
}
public static IObservable<TAccumulate> Scan<TSource, TAccumulate>(this IObservable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator)
{
return new ScanObservable<TSource, TAccumulate>(source, seed, accumulator);
}
public static IObservable<TSource> Aggregate<TSource>(this IObservable<TSource> source, Func<TSource, TSource, TSource> accumulator)
{
return new AggregateObservable<TSource>(source, accumulator);
}
public static IObservable<TAccumulate> Aggregate<TSource, TAccumulate>(this IObservable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator)
{
return new AggregateObservable<TSource, TAccumulate>(source, seed, accumulator);
}
public static IObservable<TResult> Aggregate<TSource, TAccumulate, TResult>(this IObservable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector)
{
return new AggregateObservable<TSource, TAccumulate, TResult>(source, seed, accumulator, resultSelector);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 82339dddb2a9f944785f1555b83d667c
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,133 @@
#if (NET_4_6 || NET_STANDARD_2_0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace UniRx
{
public static partial class Observable
{
/// <summary>
/// Gets an awaiter that returns the last value of the observable sequence or throws an exception if the sequence is empty.
/// This operation subscribes to the observable sequence, making it hot.
/// </summary>
/// <param name="source">Source sequence to await.</param>
public static AsyncSubject<TSource> GetAwaiter<TSource>(this IObservable<TSource> source)
{
if (source == null) throw new ArgumentNullException("source");
return RunAsync(source, CancellationToken.None);
}
/// <summary>
/// Gets an awaiter that returns the last value of the observable sequence or throws an exception if the sequence is empty.
/// This operation subscribes to the observable sequence, making it hot.
/// </summary>
/// <param name="source">Source sequence to await.</param>
public static AsyncSubject<TSource> GetAwaiter<TSource>(this IConnectableObservable<TSource> source)
{
if (source == null) throw new ArgumentNullException("source");
return RunAsync(source, CancellationToken.None);
}
/// <summary>
/// Gets an awaiter that returns the last value of the observable sequence or throws an exception if the sequence is empty.
/// This operation subscribes to the observable sequence, making it hot.
/// </summary>
/// <param name="source">Source sequence to await.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static AsyncSubject<TSource> GetAwaiter<TSource>(this IObservable<TSource> source, CancellationToken cancellationToken)
{
if (source == null) throw new ArgumentNullException("source");
return RunAsync(source, cancellationToken);
}
/// <summary>
/// Gets an awaiter that returns the last value of the observable sequence or throws an exception if the sequence is empty.
/// This operation subscribes to the observable sequence, making it hot.
/// </summary>
/// <param name="source">Source sequence to await.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static AsyncSubject<TSource> GetAwaiter<TSource>(this IConnectableObservable<TSource> source, CancellationToken cancellationToken)
{
if (source == null) throw new ArgumentNullException("source");
return RunAsync(source, cancellationToken);
}
static AsyncSubject<TSource> RunAsync<TSource>(IObservable<TSource> source, CancellationToken cancellationToken)
{
var s = new AsyncSubject<TSource>();
if (cancellationToken.IsCancellationRequested)
{
return Cancel(s, cancellationToken);
}
var d = source.Subscribe(s);
if (cancellationToken.CanBeCanceled)
{
RegisterCancelation(s, d, cancellationToken);
}
return s;
}
static AsyncSubject<TSource> RunAsync<TSource>(IConnectableObservable<TSource> source, CancellationToken cancellationToken)
{
var s = new AsyncSubject<TSource>();
if (cancellationToken.IsCancellationRequested)
{
return Cancel(s, cancellationToken);
}
var d = source.Subscribe(s);
var c = source.Connect();
if (cancellationToken.CanBeCanceled)
{
RegisterCancelation(s, StableCompositeDisposable.Create(d, c), cancellationToken);
}
return s;
}
static AsyncSubject<T> Cancel<T>(AsyncSubject<T> subject, CancellationToken cancellationToken)
{
subject.OnError(new OperationCanceledException(cancellationToken));
return subject;
}
static void RegisterCancelation<T>(AsyncSubject<T> subject, IDisposable subscription, CancellationToken token)
{
//
// Separate method used to avoid heap allocation of closure when no cancellation is needed,
// e.g. when CancellationToken.None is provided to the RunAsync overloads.
//
var ctr = token.Register(() =>
{
subscription.Dispose();
Cancel(subject, token);
});
//
// No null-check for ctr is needed:
//
// - CancellationTokenRegistration is a struct
// - Registration will succeed 99% of the time, no warranting an attempt to avoid spurious Subscribe calls
//
subject.Subscribe(Stubs<T>.Ignore, _ => ctr.Dispose(), ctr.Dispose);
}
}
}
#endif

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ec3ea3f22d061964c8f06eb9ea78ec42
timeCreated: 1475137543
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,76 @@
using System;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IConnectableObservable<T> Multicast<T>(this IObservable<T> source, ISubject<T> subject)
{
return new ConnectableObservable<T>(source, subject);
}
public static IConnectableObservable<T> Publish<T>(this IObservable<T> source)
{
return source.Multicast(new Subject<T>());
}
public static IConnectableObservable<T> Publish<T>(this IObservable<T> source, T initialValue)
{
return source.Multicast(new BehaviorSubject<T>(initialValue));
}
public static IConnectableObservable<T> PublishLast<T>(this IObservable<T> source)
{
return source.Multicast(new AsyncSubject<T>());
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source)
{
return source.Multicast(new ReplaySubject<T>());
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, IScheduler scheduler)
{
return source.Multicast(new ReplaySubject<T>(scheduler));
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, int bufferSize)
{
return source.Multicast(new ReplaySubject<T>(bufferSize));
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, int bufferSize, IScheduler scheduler)
{
return source.Multicast(new ReplaySubject<T>(bufferSize, scheduler));
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, TimeSpan window)
{
return source.Multicast(new ReplaySubject<T>(window));
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, TimeSpan window, IScheduler scheduler)
{
return source.Multicast(new ReplaySubject<T>(window, scheduler));
}
public static IConnectableObservable<T> Replay<T>(this IObservable<T> source, int bufferSize, TimeSpan window, IScheduler scheduler)
{
return source.Multicast(new ReplaySubject<T>(bufferSize, window, scheduler));
}
public static IObservable<T> RefCount<T>(this IConnectableObservable<T> source)
{
return new RefCountObservable<T>(source);
}
/// <summary>
/// same as Publish().RefCount()
/// </summary>
public static IObservable<T> Share<T>(this IObservable<T> source)
{
return source.Publish().RefCount();
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: bb11a562e64264645b76ad3a8d15d966
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,17 @@
using System;
namespace UniRx
{
public static partial class Observable
{
public static T Wait<T>(this IObservable<T> source)
{
return new UniRx.Operators.Wait<T>(source, InfiniteTimeSpan).Run();
}
public static T Wait<T>(this IObservable<T> source, TimeSpan timeout)
{
return new UniRx.Operators.Wait<T>(source, timeout).Run();
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4a05ec8aabbdba24388b7b2ae6c4a474
timeCreated: 1455373898
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,320 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using UniRx.Operators;
namespace UniRx
{
// concatenate multiple observable
// merge, concat, zip...
public static partial class Observable
{
static IEnumerable<IObservable<T>> CombineSources<T>(IObservable<T> first, IObservable<T>[] seconds)
{
yield return first;
for (int i = 0; i < seconds.Length; i++)
{
yield return seconds[i];
}
}
public static IObservable<TSource> Concat<TSource>(params IObservable<TSource>[] sources)
{
if (sources == null) throw new ArgumentNullException("sources");
return new ConcatObservable<TSource>(sources);
}
public static IObservable<TSource> Concat<TSource>(this IEnumerable<IObservable<TSource>> sources)
{
if (sources == null) throw new ArgumentNullException("sources");
return new ConcatObservable<TSource>(sources);
}
public static IObservable<TSource> Concat<TSource>(this IObservable<IObservable<TSource>> sources)
{
return sources.Merge(maxConcurrent: 1);
}
public static IObservable<TSource> Concat<TSource>(this IObservable<TSource> first, params IObservable<TSource>[] seconds)
{
if (first == null) throw new ArgumentNullException("first");
if (seconds == null) throw new ArgumentNullException("seconds");
var concat = first as ConcatObservable<TSource>;
if (concat != null)
{
return concat.Combine(seconds);
}
return Concat(CombineSources(first, seconds));
}
public static IObservable<TSource> Merge<TSource>(this IEnumerable<IObservable<TSource>> sources)
{
return Merge(sources, Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
public static IObservable<TSource> Merge<TSource>(this IEnumerable<IObservable<TSource>> sources, IScheduler scheduler)
{
return new MergeObservable<TSource>(sources.ToObservable(scheduler), scheduler == Scheduler.CurrentThread);
}
public static IObservable<TSource> Merge<TSource>(this IEnumerable<IObservable<TSource>> sources, int maxConcurrent)
{
return Merge(sources, maxConcurrent, Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
public static IObservable<TSource> Merge<TSource>(this IEnumerable<IObservable<TSource>> sources, int maxConcurrent, IScheduler scheduler)
{
return new MergeObservable<TSource>(sources.ToObservable(scheduler), maxConcurrent, scheduler == Scheduler.CurrentThread);
}
public static IObservable<TSource> Merge<TSource>(params IObservable<TSource>[] sources)
{
return Merge(Scheduler.DefaultSchedulers.ConstantTimeOperations, sources);
}
public static IObservable<TSource> Merge<TSource>(IScheduler scheduler, params IObservable<TSource>[] sources)
{
return new MergeObservable<TSource>(sources.ToObservable(scheduler), scheduler == Scheduler.CurrentThread);
}
public static IObservable<T> Merge<T>(this IObservable<T> first, params IObservable<T>[] seconds)
{
return Merge(CombineSources(first, seconds));
}
public static IObservable<T> Merge<T>(this IObservable<T> first, IObservable<T> second, IScheduler scheduler)
{
return Merge(scheduler, new[] { first, second });
}
public static IObservable<T> Merge<T>(this IObservable<IObservable<T>> sources)
{
return new MergeObservable<T>(sources, false);
}
public static IObservable<T> Merge<T>(this IObservable<IObservable<T>> sources, int maxConcurrent)
{
return new MergeObservable<T>(sources, maxConcurrent, false);
}
public static IObservable<TResult> Zip<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> selector)
{
return new ZipObservable<TLeft, TRight, TResult>(left, right, selector);
}
public static IObservable<IList<T>> Zip<T>(this IEnumerable<IObservable<T>> sources)
{
return Zip(sources.ToArray());
}
public static IObservable<IList<T>> Zip<T>(params IObservable<T>[] sources)
{
return new ZipObservable<T>(sources);
}
public static IObservable<TR> Zip<T1, T2, T3, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, ZipFunc<T1, T2, T3, TR> resultSelector)
{
return new ZipObservable<T1, T2, T3, TR>(source1, source2, source3, resultSelector);
}
public static IObservable<TR> Zip<T1, T2, T3, T4, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, ZipFunc<T1, T2, T3, T4, TR> resultSelector)
{
return new ZipObservable<T1, T2, T3, T4, TR>(source1, source2, source3, source4, resultSelector);
}
public static IObservable<TR> Zip<T1, T2, T3, T4, T5, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, ZipFunc<T1, T2, T3, T4, T5, TR> resultSelector)
{
return new ZipObservable<T1, T2, T3, T4, T5, TR>(source1, source2, source3, source4, source5, resultSelector);
}
public static IObservable<TR> Zip<T1, T2, T3, T4, T5, T6, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, ZipFunc<T1, T2, T3, T4, T5, T6, TR> resultSelector)
{
return new ZipObservable<T1, T2, T3, T4, T5, T6, TR>(source1, source2, source3, source4, source5, source6, resultSelector);
}
public static IObservable<TR> Zip<T1, T2, T3, T4, T5, T6, T7, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, IObservable<T7> source7, ZipFunc<T1, T2, T3, T4, T5, T6, T7, TR> resultSelector)
{
return new ZipObservable<T1, T2, T3, T4, T5, T6, T7, TR>(source1, source2, source3, source4, source5, source6, source7, resultSelector);
}
public static IObservable<TResult> CombineLatest<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> selector)
{
return new CombineLatestObservable<TLeft, TRight, TResult>(left, right, selector);
}
public static IObservable<IList<T>> CombineLatest<T>(this IEnumerable<IObservable<T>> sources)
{
return CombineLatest(sources.ToArray());
}
public static IObservable<IList<TSource>> CombineLatest<TSource>(params IObservable<TSource>[] sources)
{
return new CombineLatestObservable<TSource>(sources);
}
public static IObservable<TR> CombineLatest<T1, T2, T3, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, CombineLatestFunc<T1, T2, T3, TR> resultSelector)
{
return new CombineLatestObservable<T1, T2, T3, TR>(source1, source2, source3, resultSelector);
}
public static IObservable<TR> CombineLatest<T1, T2, T3, T4, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, CombineLatestFunc<T1, T2, T3, T4, TR> resultSelector)
{
return new CombineLatestObservable<T1, T2, T3, T4, TR>(source1, source2, source3, source4, resultSelector);
}
public static IObservable<TR> CombineLatest<T1, T2, T3, T4, T5, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, CombineLatestFunc<T1, T2, T3, T4, T5, TR> resultSelector)
{
return new CombineLatestObservable<T1, T2, T3, T4, T5, TR>(source1, source2, source3, source4, source5, resultSelector);
}
public static IObservable<TR> CombineLatest<T1, T2, T3, T4, T5, T6, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, CombineLatestFunc<T1, T2, T3, T4, T5, T6, TR> resultSelector)
{
return new CombineLatestObservable<T1, T2, T3, T4, T5, T6, TR>(source1, source2, source3, source4, source5, source6, resultSelector);
}
public static IObservable<TR> CombineLatest<T1, T2, T3, T4, T5, T6, T7, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, IObservable<T7> source7, CombineLatestFunc<T1, T2, T3, T4, T5, T6, T7, TR> resultSelector)
{
return new CombineLatestObservable<T1, T2, T3, T4, T5, T6, T7, TR>(source1, source2, source3, source4, source5, source6, source7, resultSelector);
}
public static IObservable<TResult> ZipLatest<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> selector)
{
return new ZipLatestObservable<TLeft, TRight, TResult>(left, right, selector);
}
public static IObservable<IList<T>> ZipLatest<T>(this IEnumerable<IObservable<T>> sources)
{
return ZipLatest(sources.ToArray());
}
public static IObservable<IList<TSource>> ZipLatest<TSource>(params IObservable<TSource>[] sources)
{
return new ZipLatestObservable<TSource>(sources);
}
public static IObservable<TR> ZipLatest<T1, T2, T3, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, ZipLatestFunc<T1, T2, T3, TR> resultSelector)
{
return new ZipLatestObservable<T1, T2, T3, TR>(source1, source2, source3, resultSelector);
}
public static IObservable<TR> ZipLatest<T1, T2, T3, T4, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, ZipLatestFunc<T1, T2, T3, T4, TR> resultSelector)
{
return new ZipLatestObservable<T1, T2, T3, T4, TR>(source1, source2, source3, source4, resultSelector);
}
public static IObservable<TR> ZipLatest<T1, T2, T3, T4, T5, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, ZipLatestFunc<T1, T2, T3, T4, T5, TR> resultSelector)
{
return new ZipLatestObservable<T1, T2, T3, T4, T5, TR>(source1, source2, source3, source4, source5, resultSelector);
}
public static IObservable<TR> ZipLatest<T1, T2, T3, T4, T5, T6, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, ZipLatestFunc<T1, T2, T3, T4, T5, T6, TR> resultSelector)
{
return new ZipLatestObservable<T1, T2, T3, T4, T5, T6, TR>(source1, source2, source3, source4, source5, source6, resultSelector);
}
public static IObservable<TR> ZipLatest<T1, T2, T3, T4, T5, T6, T7, TR>(this IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, IObservable<T7> source7, ZipLatestFunc<T1, T2, T3, T4, T5, T6, T7, TR> resultSelector)
{
return new ZipLatestObservable<T1, T2, T3, T4, T5, T6, T7, TR>(source1, source2, source3, source4, source5, source6, source7, resultSelector);
}
public static IObservable<T> Switch<T>(this IObservable<IObservable<T>> sources)
{
return new SwitchObservable<T>(sources);
}
public static IObservable<TResult> WithLatestFrom<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> selector)
{
return new WithLatestFromObservable<TLeft, TRight, TResult>(left, right, selector);
}
/// <summary>
/// <para>Specialized for single async operations like Task.WhenAll, Zip.Take(1).</para>
/// <para>If sequence is empty, return T[0] array.</para>
/// </summary>
public static IObservable<T[]> WhenAll<T>(params IObservable<T>[] sources)
{
if (sources.Length == 0) return Observable.Return(new T[0]);
return new WhenAllObservable<T>(sources);
}
/// <summary>
/// <para>Specialized for single async operations like Task.WhenAll, Zip.Take(1).</para>
/// </summary>
public static IObservable<Unit> WhenAll(params IObservable<Unit>[] sources)
{
if (sources.Length == 0) return Observable.ReturnUnit();
return new WhenAllObservable(sources);
}
/// <summary>
/// <para>Specialized for single async operations like Task.WhenAll, Zip.Take(1).</para>
/// <para>If sequence is empty, return T[0] array.</para>
/// </summary>
public static IObservable<T[]> WhenAll<T>(this IEnumerable<IObservable<T>> sources)
{
var array = sources as IObservable<T>[];
if (array != null) return WhenAll(array);
return new WhenAllObservable<T>(sources);
}
/// <summary>
/// <para>Specialized for single async operations like Task.WhenAll, Zip.Take(1).</para>
/// </summary>
public static IObservable<Unit> WhenAll(this IEnumerable<IObservable<Unit>> sources)
{
var array = sources as IObservable<Unit>[];
if (array != null) return WhenAll(array);
return new WhenAllObservable(sources);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, T value)
{
return new StartWithObservable<T>(source, value);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, Func<T> valueFactory)
{
return new StartWithObservable<T>(source, valueFactory);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, params T[] values)
{
return StartWith(source, Scheduler.DefaultSchedulers.ConstantTimeOperations, values);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, IEnumerable<T> values)
{
return StartWith(source, Scheduler.DefaultSchedulers.ConstantTimeOperations, values);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, IScheduler scheduler, T value)
{
return Observable.Return(value, scheduler).Concat(source);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, IScheduler scheduler, IEnumerable<T> values)
{
var array = values as T[];
if (array == null)
{
array = values.ToArray();
}
return StartWith(source, scheduler, array);
}
public static IObservable<T> StartWith<T>(this IObservable<T> source, IScheduler scheduler, params T[] values)
{
return values.ToObservable(scheduler).Concat(source);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 18c56bbfaaeedf445874f4246d42b509
timeCreated: 1455373897
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Text;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IObservable<T> Synchronize<T>(this IObservable<T> source)
{
return new SynchronizeObservable<T>(source, new object());
}
public static IObservable<T> Synchronize<T>(this IObservable<T> source, object gate)
{
return new SynchronizeObservable<T>(source, gate);
}
public static IObservable<T> ObserveOn<T>(this IObservable<T> source, IScheduler scheduler)
{
return new ObserveOnObservable<T>(source, scheduler);
}
public static IObservable<T> SubscribeOn<T>(this IObservable<T> source, IScheduler scheduler)
{
return new SubscribeOnObservable<T>(source, scheduler);
}
public static IObservable<T> DelaySubscription<T>(this IObservable<T> source, TimeSpan dueTime)
{
return new DelaySubscriptionObservable<T>(source, dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> DelaySubscription<T>(this IObservable<T> source, TimeSpan dueTime, IScheduler scheduler)
{
return new DelaySubscriptionObservable<T>(source, dueTime, scheduler);
}
public static IObservable<T> DelaySubscription<T>(this IObservable<T> source, DateTimeOffset dueTime)
{
return new DelaySubscriptionObservable<T>(source, dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> DelaySubscription<T>(this IObservable<T> source, DateTimeOffset dueTime, IScheduler scheduler)
{
return new DelaySubscriptionObservable<T>(source, dueTime, scheduler);
}
public static IObservable<T> Amb<T>(params IObservable<T>[] sources)
{
return Amb((IEnumerable<IObservable<T>>)sources);
}
public static IObservable<T> Amb<T>(IEnumerable<IObservable<T>> sources)
{
var result = Observable.Never<T>();
foreach (var item in sources)
{
var second = item;
result = result.Amb(second);
}
return result;
}
public static IObservable<T> Amb<T>(this IObservable<T> source, IObservable<T> second)
{
return new AmbObservable<T>(source, second);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a31d38ad13dc4644180647afc28c6045
timeCreated: 1455373900
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IObservable<T> AsObservable<T>(this IObservable<T> source)
{
if (source == null) throw new ArgumentNullException("source");
// optimize, don't double wrap
if (source is UniRx.Operators.AsObservableObservable<T>)
{
return source;
}
return new AsObservableObservable<T>(source);
}
public static IObservable<T> ToObservable<T>(this IEnumerable<T> source)
{
return ToObservable(source, Scheduler.DefaultSchedulers.Iteration);
}
public static IObservable<T> ToObservable<T>(this IEnumerable<T> source, IScheduler scheduler)
{
return new ToObservableObservable<T>(source, scheduler);
}
public static IObservable<TResult> Cast<TSource, TResult>(this IObservable<TSource> source)
{
return new CastObservable<TSource, TResult>(source);
}
/// <summary>
/// witness is for type inference.
/// </summary>
public static IObservable<TResult> Cast<TSource, TResult>(this IObservable<TSource> source, TResult witness)
{
return new CastObservable<TSource, TResult>(source);
}
public static IObservable<TResult> OfType<TSource, TResult>(this IObservable<TSource> source)
{
return new OfTypeObservable<TSource, TResult>(source);
}
/// <summary>
/// witness is for type inference.
/// </summary>
public static IObservable<TResult> OfType<TSource, TResult>(this IObservable<TSource> source, TResult witness)
{
return new OfTypeObservable<TSource, TResult>(source);
}
/// <summary>
/// Converting .Select(_ => Unit.Default) sequence.
/// </summary>
public static IObservable<Unit> AsUnitObservable<T>(this IObservable<T> source)
{
return new AsUnitObservableObservable<T>(source);
}
/// <summary>
/// Same as LastOrDefault().AsUnitObservable().
/// </summary>
public static IObservable<Unit> AsSingleUnitObservable<T>(this IObservable<T> source)
{
return new AsSingleUnitObservableObservable<T>(source);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e32bd7bbf28014b4ab2873cc8de3dea9
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,375 @@
using System;
using System.Collections.Generic;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
/// <summary>
/// Create anonymous observable. Observer has exception durability. This is recommended for make operator and event like generator.
/// </summary>
public static IObservable<T> Create<T>(Func<IObserver<T>, IDisposable> subscribe)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateObservable<T>(subscribe);
}
/// <summary>
/// Create anonymous observable. Observer has exception durability. This is recommended for make operator and event like generator(HotObservable).
/// </summary>
public static IObservable<T> Create<T>(Func<IObserver<T>, IDisposable> subscribe, bool isRequiredSubscribeOnCurrentThread)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateObservable<T>(subscribe, isRequiredSubscribeOnCurrentThread);
}
/// <summary>
/// Create anonymous observable. Observer has exception durability. This is recommended for make operator and event like generator.
/// </summary>
public static IObservable<T> CreateWithState<T, TState>(TState state, Func<TState, IObserver<T>, IDisposable> subscribe)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateObservable<T, TState>(state, subscribe);
}
/// <summary>
/// Create anonymous observable. Observer has exception durability. This is recommended for make operator and event like generator(HotObservable).
/// </summary>
public static IObservable<T> CreateWithState<T, TState>(TState state, Func<TState, IObserver<T>, IDisposable> subscribe, bool isRequiredSubscribeOnCurrentThread)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateObservable<T, TState>(state, subscribe, isRequiredSubscribeOnCurrentThread);
}
/// <summary>
/// Create anonymous observable. Safe means auto detach when error raised in onNext pipeline. This is recommended for make generator (ColdObservable).
/// </summary>
public static IObservable<T> CreateSafe<T>(Func<IObserver<T>, IDisposable> subscribe)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateSafeObservable<T>(subscribe);
}
/// <summary>
/// Create anonymous observable. Safe means auto detach when error raised in onNext pipeline. This is recommended for make generator (ColdObservable).
/// </summary>
public static IObservable<T> CreateSafe<T>(Func<IObserver<T>, IDisposable> subscribe, bool isRequiredSubscribeOnCurrentThread)
{
if (subscribe == null) throw new ArgumentNullException("subscribe");
return new CreateSafeObservable<T>(subscribe, isRequiredSubscribeOnCurrentThread);
}
/// <summary>
/// Empty Observable. Returns only OnCompleted.
/// </summary>
public static IObservable<T> Empty<T>()
{
return Empty<T>(Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
/// <summary>
/// Empty Observable. Returns only OnCompleted on specified scheduler.
/// </summary>
public static IObservable<T> Empty<T>(IScheduler scheduler)
{
if (scheduler == Scheduler.Immediate)
{
return ImmutableEmptyObservable<T>.Instance;
}
else
{
return new EmptyObservable<T>(scheduler);
}
}
/// <summary>
/// Empty Observable. Returns only OnCompleted. witness is for type inference.
/// </summary>
public static IObservable<T> Empty<T>(T witness)
{
return Empty<T>(Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
/// <summary>
/// Empty Observable. Returns only OnCompleted on specified scheduler. witness is for type inference.
/// </summary>
public static IObservable<T> Empty<T>(IScheduler scheduler, T witness)
{
return Empty<T>(scheduler);
}
/// <summary>
/// Non-Terminating Observable. It's no returns, never finish.
/// </summary>
public static IObservable<T> Never<T>()
{
return ImmutableNeverObservable<T>.Instance;
}
/// <summary>
/// Non-Terminating Observable. It's no returns, never finish. witness is for type inference.
/// </summary>
public static IObservable<T> Never<T>(T witness)
{
return ImmutableNeverObservable<T>.Instance;
}
/// <summary>
/// Return single sequence Immediately.
/// </summary>
public static IObservable<T> Return<T>(T value)
{
return Return<T>(value, Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
/// <summary>
/// Return single sequence on specified scheduler.
/// </summary>
public static IObservable<T> Return<T>(T value, IScheduler scheduler)
{
if (scheduler == Scheduler.Immediate)
{
return new ImmediateReturnObservable<T>(value);
}
else
{
return new ReturnObservable<T>(value, scheduler);
}
}
/// <summary>
/// Return single sequence Immediately, optimized for Unit(no allocate memory).
/// </summary>
public static IObservable<Unit> Return(Unit value)
{
return ImmutableReturnUnitObservable.Instance;
}
/// <summary>
/// Return single sequence Immediately, optimized for Boolean(no allocate memory).
/// </summary>
public static IObservable<bool> Return(bool value)
{
return (value == true)
? (IObservable<bool>)ImmutableReturnTrueObservable.Instance
: (IObservable<bool>)ImmutableReturnFalseObservable.Instance;
}
/// <summary>
/// Return single sequence Immediately, optimized for Int32.
/// </summary>
public static IObservable<Int32> Return(int value)
{
return ImmutableReturnInt32Observable.GetInt32Observable(value);
}
/// <summary>
/// Same as Observable.Return(Unit.Default); but no allocate memory.
/// </summary>
public static IObservable<Unit> ReturnUnit()
{
return ImmutableReturnUnitObservable.Instance;
}
/// <summary>
/// Empty Observable. Returns only onError.
/// </summary>
public static IObservable<T> Throw<T>(Exception error)
{
return Throw<T>(error, Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
/// <summary>
/// Empty Observable. Returns only onError. witness if for Type inference.
/// </summary>
public static IObservable<T> Throw<T>(Exception error, T witness)
{
return Throw<T>(error, Scheduler.DefaultSchedulers.ConstantTimeOperations);
}
/// <summary>
/// Empty Observable. Returns only onError on specified scheduler.
/// </summary>
public static IObservable<T> Throw<T>(Exception error, IScheduler scheduler)
{
return new ThrowObservable<T>(error, scheduler);
}
/// <summary>
/// Empty Observable. Returns only onError on specified scheduler. witness if for Type inference.
/// </summary>
public static IObservable<T> Throw<T>(Exception error, IScheduler scheduler, T witness)
{
return Throw<T>(error, scheduler);
}
public static IObservable<int> Range(int start, int count)
{
return Range(start, count, Scheduler.DefaultSchedulers.Iteration);
}
public static IObservable<int> Range(int start, int count, IScheduler scheduler)
{
return new RangeObservable(start, count, scheduler);
}
public static IObservable<T> Repeat<T>(T value)
{
return Repeat(value, Scheduler.DefaultSchedulers.Iteration);
}
public static IObservable<T> Repeat<T>(T value, IScheduler scheduler)
{
if (scheduler == null) throw new ArgumentNullException("scheduler");
return new RepeatObservable<T>(value, null, scheduler);
}
public static IObservable<T> Repeat<T>(T value, int repeatCount)
{
return Repeat(value, repeatCount, Scheduler.DefaultSchedulers.Iteration);
}
public static IObservable<T> Repeat<T>(T value, int repeatCount, IScheduler scheduler)
{
if (repeatCount < 0) throw new ArgumentOutOfRangeException("repeatCount");
if (scheduler == null) throw new ArgumentNullException("scheduler");
return new RepeatObservable<T>(value, repeatCount, scheduler);
}
public static IObservable<T> Repeat<T>(this IObservable<T> source)
{
return RepeatInfinite(source).Concat();
}
static IEnumerable<IObservable<T>> RepeatInfinite<T>(IObservable<T> source)
{
while (true)
{
yield return source;
}
}
/// <summary>
/// Same as Repeat() but if arriving contiguous "OnComplete" Repeat stops.
/// </summary>
public static IObservable<T> RepeatSafe<T>(this IObservable<T> source)
{
return new RepeatSafeObservable<T>(RepeatInfinite(source), source.IsRequiredSubscribeOnCurrentThread());
}
public static IObservable<T> Defer<T>(Func<IObservable<T>> observableFactory)
{
return new DeferObservable<T>(observableFactory);
}
public static IObservable<T> Start<T>(Func<T> function)
{
return new StartObservable<T>(function, null, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static IObservable<T> Start<T>(Func<T> function, TimeSpan timeSpan)
{
return new StartObservable<T>(function, timeSpan, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static IObservable<T> Start<T>(Func<T> function, IScheduler scheduler)
{
return new StartObservable<T>(function, null, scheduler);
}
public static IObservable<T> Start<T>(Func<T> function, TimeSpan timeSpan, IScheduler scheduler)
{
return new StartObservable<T>(function, timeSpan, scheduler);
}
public static IObservable<Unit> Start(Action action)
{
return new StartObservable<Unit>(action, null, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static IObservable<Unit> Start(Action action, TimeSpan timeSpan)
{
return new StartObservable<Unit>(action, timeSpan, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static IObservable<Unit> Start(Action action, IScheduler scheduler)
{
return new StartObservable<Unit>(action, null, scheduler);
}
public static IObservable<Unit> Start(Action action, TimeSpan timeSpan, IScheduler scheduler)
{
return new StartObservable<Unit>(action, timeSpan, scheduler);
}
public static Func<IObservable<T>> ToAsync<T>(Func<T> function)
{
return ToAsync(function, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static Func<IObservable<T>> ToAsync<T>(Func<T> function, IScheduler scheduler)
{
return () =>
{
var subject = new AsyncSubject<T>();
scheduler.Schedule(() =>
{
var result = default(T);
try
{
result = function();
}
catch (Exception exception)
{
subject.OnError(exception);
return;
}
subject.OnNext(result);
subject.OnCompleted();
});
return subject.AsObservable();
};
}
public static Func<IObservable<Unit>> ToAsync(Action action)
{
return ToAsync(action, Scheduler.DefaultSchedulers.AsyncConversions);
}
public static Func<IObservable<Unit>> ToAsync(Action action, IScheduler scheduler)
{
return () =>
{
var subject = new AsyncSubject<Unit>();
scheduler.Schedule(() =>
{
try
{
action();
}
catch (Exception exception)
{
subject.OnError(exception);
return;
}
subject.OnNext(Unit.Default);
subject.OnCompleted();
});
return subject.AsObservable();
};
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e63036d2dba75f64382beed512fd086c
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,134 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IObservable<T> Finally<T>(this IObservable<T> source, Action finallyAction)
{
return new FinallyObservable<T>(source, finallyAction);
}
public static IObservable<T> Catch<T, TException>(this IObservable<T> source, Func<TException, IObservable<T>> errorHandler)
where TException : Exception
{
return new CatchObservable<T, TException>(source, errorHandler);
}
public static IObservable<TSource> Catch<TSource>(this IEnumerable<IObservable<TSource>> sources)
{
return new CatchObservable<TSource>(sources);
}
/// <summary>Catch exception and return Observable.Empty.</summary>
public static IObservable<TSource> CatchIgnore<TSource>(this IObservable<TSource> source)
{
return source.Catch<TSource, Exception>(Stubs.CatchIgnore<TSource>);
}
/// <summary>Catch exception and return Observable.Empty.</summary>
public static IObservable<TSource> CatchIgnore<TSource, TException>(this IObservable<TSource> source, Action<TException> errorAction)
where TException : Exception
{
var result = source.Catch((TException ex) =>
{
errorAction(ex);
return Observable.Empty<TSource>();
});
return result;
}
public static IObservable<TSource> Retry<TSource>(this IObservable<TSource> source)
{
return RepeatInfinite(source).Catch();
}
public static IObservable<TSource> Retry<TSource>(this IObservable<TSource> source, int retryCount)
{
return System.Linq.Enumerable.Repeat(source, retryCount).Catch();
}
/// <summary>
/// <para>Repeats the source observable sequence until it successfully terminates.</para>
/// <para>This is same as Retry().</para>
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource>(
this IObservable<TSource> source)
{
var result = source.Retry();
return result;
}
/// <summary>
/// When catched exception, do onError action and repeat observable sequence.
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource, TException>(
this IObservable<TSource> source, Action<TException> onError)
where TException : Exception
{
return source.OnErrorRetry(onError, TimeSpan.Zero);
}
/// <summary>
/// When catched exception, do onError action and repeat observable sequence after delay time.
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource, TException>(
this IObservable<TSource> source, Action<TException> onError, TimeSpan delay)
where TException : Exception
{
return source.OnErrorRetry(onError, int.MaxValue, delay);
}
/// <summary>
/// When catched exception, do onError action and repeat observable sequence during within retryCount.
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource, TException>(
this IObservable<TSource> source, Action<TException> onError, int retryCount)
where TException : Exception
{
return source.OnErrorRetry(onError, retryCount, TimeSpan.Zero);
}
/// <summary>
/// When catched exception, do onError action and repeat observable sequence after delay time during within retryCount.
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource, TException>(
this IObservable<TSource> source, Action<TException> onError, int retryCount, TimeSpan delay)
where TException : Exception
{
return source.OnErrorRetry(onError, retryCount, delay, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
/// <summary>
/// When catched exception, do onError action and repeat observable sequence after delay time(work on delayScheduler) during within retryCount.
/// </summary>
public static IObservable<TSource> OnErrorRetry<TSource, TException>(
this IObservable<TSource> source, Action<TException> onError, int retryCount, TimeSpan delay, IScheduler delayScheduler)
where TException : Exception
{
var result = Observable.Defer(() =>
{
var dueTime = (delay.Ticks < 0) ? TimeSpan.Zero : delay;
var count = 0;
IObservable<TSource> self = null;
self = source.Catch((TException ex) =>
{
onError(ex);
return (++count < retryCount)
? (dueTime == TimeSpan.Zero)
? self.SubscribeOn(Scheduler.CurrentThread)
: self.DelaySubscription(dueTime, delayScheduler).SubscribeOn(Scheduler.CurrentThread)
: Observable.Throw<TSource>(ex);
});
return self;
});
return result;
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f40cab35efe24e6448ac8455bc7a4eb9
timeCreated: 1455373902
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,34 @@
using System;
using UniRx.Operators;
namespace UniRx
{
public static partial class Observable
{
public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TDelegate, TEventArgs>(Func<EventHandler<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler)
where TEventArgs : EventArgs
{
return new FromEventPatternObservable<TDelegate, TEventArgs>(conversion, addHandler, removeHandler);
}
public static IObservable<Unit> FromEvent<TDelegate>(Func<Action, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler)
{
return new FromEventObservable<TDelegate>(conversion, addHandler, removeHandler);
}
public static IObservable<TEventArgs> FromEvent<TDelegate, TEventArgs>(Func<Action<TEventArgs>, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler)
{
return new FromEventObservable<TDelegate, TEventArgs>(conversion, addHandler, removeHandler);
}
public static IObservable<Unit> FromEvent(Action<Action> addHandler, Action<Action> removeHandler)
{
return new FromEventObservable(addHandler, removeHandler);
}
public static IObservable<T> FromEvent<T>(Action<Action<T>> addHandler, Action<Action<T>> removeHandler)
{
return new FromEventObservable_<T>(addHandler, removeHandler);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e591aafff0492c94590cf9702f6c408f
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,127 @@
using System;
namespace UniRx
{
public static partial class Observable
{
public static Func<IObservable<TResult>> FromAsyncPattern<TResult>(Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, TResult> end)
{
return () =>
{
var subject = new AsyncSubject<TResult>();
try
{
begin(iar =>
{
TResult result;
try
{
result = end(iar);
}
catch (Exception exception)
{
subject.OnError(exception);
return;
}
subject.OnNext(result);
subject.OnCompleted();
}, null);
}
catch (Exception exception)
{
return Observable.Throw<TResult>(exception, Scheduler.DefaultSchedulers.AsyncConversions);
}
return subject.AsObservable();
};
}
public static Func<T1, IObservable<TResult>> FromAsyncPattern<T1, TResult>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, TResult> end)
{
return x =>
{
var subject = new AsyncSubject<TResult>();
try
{
begin(x, iar =>
{
TResult result;
try
{
result = end(iar);
}
catch (Exception exception)
{
subject.OnError(exception);
return;
}
subject.OnNext(result);
subject.OnCompleted();
}, null);
}
catch (Exception exception)
{
return Observable.Throw<TResult>(exception, Scheduler.DefaultSchedulers.AsyncConversions);
}
return subject.AsObservable();
};
}
public static Func<T1, T2, IObservable<TResult>> FromAsyncPattern<T1, T2, TResult>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, TResult> end)
{
return (x, y) =>
{
var subject = new AsyncSubject<TResult>();
try
{
begin(x, y, iar =>
{
TResult result;
try
{
result = end(iar);
}
catch (Exception exception)
{
subject.OnError(exception);
return;
}
subject.OnNext(result);
subject.OnCompleted();
}, null);
}
catch (Exception exception)
{
return Observable.Throw<TResult>(exception, Scheduler.DefaultSchedulers.AsyncConversions);
}
return subject.AsObservable();
};
}
public static Func<IObservable<Unit>> FromAsyncPattern(Func<AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end)
{
return FromAsyncPattern(begin, iar =>
{
end(iar);
return Unit.Default;
});
}
public static Func<T1, IObservable<Unit>> FromAsyncPattern<T1>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end)
{
return FromAsyncPattern(begin, iar =>
{
end(iar);
return Unit.Default;
});
}
public static Func<T1, T2, IObservable<Unit>> FromAsyncPattern<T1, T2>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end)
{
return FromAsyncPattern(begin, iar =>
{
end(iar);
return Unit.Default;
});
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 601f5bb7bb302a14cb46df717729b8c7
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UniRx
{
public static partial class Observable
{
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dd92425c6c6dec24e9e52677cbc36aa0
timeCreated: 1455373901
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,327 @@
using System;
using System.Collections.Generic;
using System.Text;
using UniRx.InternalUtil;
using UniRx.Operators;
namespace UniRx
{
// Take, Skip, etc..
public static partial class Observable
{
public static IObservable<T> Take<T>(this IObservable<T> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (count == 0) return Empty<T>();
// optimize .Take(count).Take(count)
var take = source as TakeObservable<T>;
if (take != null && take.scheduler == null)
{
return take.Combine(count);
}
return new TakeObservable<T>(source, count);
}
public static IObservable<T> Take<T>(this IObservable<T> source, TimeSpan duration)
{
return Take(source, duration, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> Take<T>(this IObservable<T> source, TimeSpan duration, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
if (scheduler == null) throw new ArgumentNullException("scheduler");
// optimize .Take(duration).Take(duration)
var take = source as TakeObservable<T>;
if (take != null && take.scheduler == scheduler)
{
return take.Combine(duration);
}
return new TakeObservable<T>(source, duration, scheduler);
}
public static IObservable<T> TakeWhile<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new TakeWhileObservable<T>(source, predicate);
}
public static IObservable<T> TakeWhile<T>(this IObservable<T> source, Func<T, int, bool> predicate)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
return new TakeWhileObservable<T>(source, predicate);
}
public static IObservable<T> TakeUntil<T, TOther>(this IObservable<T> source, IObservable<TOther> other)
{
if (source == null) throw new ArgumentNullException("source");
if (other == null) throw new ArgumentNullException("other");
return new TakeUntilObservable<T, TOther>(source, other);
}
public static IObservable<T> TakeLast<T>(this IObservable<T> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count");
return new TakeLastObservable<T>(source, count);
}
public static IObservable<T> TakeLast<T>(this IObservable<T> source, TimeSpan duration)
{
return TakeLast<T>(source, duration, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> TakeLast<T>(this IObservable<T> source, TimeSpan duration, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
return new TakeLastObservable<T>(source, duration, scheduler);
}
public static IObservable<T> Skip<T>(this IObservable<T> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count < 0) throw new ArgumentOutOfRangeException("count");
// optimize .Skip(count).Skip(count)
var skip = source as SkipObservable<T>;
if (skip != null && skip.scheduler == null)
{
return skip.Combine(count);
}
return new SkipObservable<T>(source, count);
}
public static IObservable<T> Skip<T>(this IObservable<T> source, TimeSpan duration)
{
return Skip(source, duration, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> Skip<T>(this IObservable<T> source, TimeSpan duration, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
if (scheduler == null) throw new ArgumentNullException("scheduler");
// optimize .Skip(duration).Skip(duration)
var skip = source as SkipObservable<T>;
if (skip != null && skip.scheduler == scheduler)
{
return skip.Combine(duration);
}
return new SkipObservable<T>(source, duration, scheduler);
}
public static IObservable<T> SkipWhile<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new SkipWhileObservable<T>(source, predicate);
}
public static IObservable<T> SkipWhile<T>(this IObservable<T> source, Func<T, int, bool> predicate)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
return new SkipWhileObservable<T>(source, predicate);
}
public static IObservable<T> SkipUntil<T, TOther>(this IObservable<T> source, IObservable<TOther> other)
{
return new SkipUntilObservable<T, TOther>(source, other);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, int count)
{
if (source == null) throw new ArgumentNullException("source");
if (count <= 0) throw new ArgumentOutOfRangeException("count <= 0");
return new BufferObservable<T>(source, count, 0);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, int count, int skip)
{
if (source == null) throw new ArgumentNullException("source");
if (count <= 0) throw new ArgumentOutOfRangeException("count <= 0");
if (skip <= 0) throw new ArgumentOutOfRangeException("skip <= 0");
return new BufferObservable<T>(source, count, skip);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan)
{
return Buffer(source, timeSpan, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
return new BufferObservable<T>(source, timeSpan, timeSpan, scheduler);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan, int count)
{
return Buffer(source, timeSpan, count, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan, int count, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
if (count <= 0) throw new ArgumentOutOfRangeException("count <= 0");
return new BufferObservable<T>(source, timeSpan, count, scheduler);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan, TimeSpan timeShift)
{
return new BufferObservable<T>(source, timeSpan, timeShift, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<IList<T>> Buffer<T>(this IObservable<T> source, TimeSpan timeSpan, TimeSpan timeShift, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
return new BufferObservable<T>(source, timeSpan, timeShift, scheduler);
}
public static IObservable<IList<TSource>> Buffer<TSource, TWindowBoundary>(this IObservable<TSource> source, IObservable<TWindowBoundary> windowBoundaries)
{
return new BufferObservable<TSource, TWindowBoundary>(source, windowBoundaries);
}
/// <summary>Projects old and new element of a sequence into a new form.</summary>
public static IObservable<Pair<T>> Pairwise<T>(this IObservable<T> source)
{
return new PairwiseObservable<T>(source);
}
/// <summary>Projects old and new element of a sequence into a new form.</summary>
public static IObservable<TR> Pairwise<T, TR>(this IObservable<T> source, Func<T, T, TR> selector)
{
return new PairwiseObservable<T, TR>(source, selector);
}
// first, last, single
public static IObservable<T> Last<T>(this IObservable<T> source)
{
return new LastObservable<T>(source, false);
}
public static IObservable<T> Last<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new LastObservable<T>(source, predicate, false);
}
public static IObservable<T> LastOrDefault<T>(this IObservable<T> source)
{
return new LastObservable<T>(source, true);
}
public static IObservable<T> LastOrDefault<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new LastObservable<T>(source, predicate, true);
}
public static IObservable<T> First<T>(this IObservable<T> source)
{
return new FirstObservable<T>(source, false);
}
public static IObservable<T> First<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new FirstObservable<T>(source, predicate, false);
}
public static IObservable<T> FirstOrDefault<T>(this IObservable<T> source)
{
return new FirstObservable<T>(source, true);
}
public static IObservable<T> FirstOrDefault<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new FirstObservable<T>(source, predicate, true);
}
public static IObservable<T> Single<T>(this IObservable<T> source)
{
return new SingleObservable<T>(source, false);
}
public static IObservable<T> Single<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new SingleObservable<T>(source, predicate, false);
}
public static IObservable<T> SingleOrDefault<T>(this IObservable<T> source)
{
return new SingleObservable<T>(source, true);
}
public static IObservable<T> SingleOrDefault<T>(this IObservable<T> source, Func<T, bool> predicate)
{
return new SingleObservable<T>(source, predicate, true);
}
// Grouping
public static IObservable<IGroupedObservable<TKey, TSource>> GroupBy<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector)
{
return GroupBy(source, keySelector, Stubs<TSource>.Identity);
}
public static IObservable<IGroupedObservable<TKey, TSource>> GroupBy<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
return GroupBy(source, keySelector, Stubs<TSource>.Identity, comparer);
}
public static IObservable<IGroupedObservable<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<TKey>();
#else
var comparer = EqualityComparer<TKey>.Default;
#endif
return GroupBy(source, keySelector, elementSelector, comparer);
}
public static IObservable<IGroupedObservable<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
return new GroupByObservable<TSource, TKey, TElement>(source, keySelector, elementSelector, null, comparer);
}
public static IObservable<IGroupedObservable<TKey, TSource>> GroupBy<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, int capacity)
{
return GroupBy(source, keySelector, Stubs<TSource>.Identity, capacity);
}
public static IObservable<IGroupedObservable<TKey, TSource>> GroupBy<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, int capacity, IEqualityComparer<TKey> comparer)
{
return GroupBy(source, keySelector, Stubs<TSource>.Identity, capacity, comparer);
}
public static IObservable<IGroupedObservable<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, int capacity)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<TKey>();
#else
var comparer = EqualityComparer<TKey>.Default;
#endif
return GroupBy(source, keySelector, elementSelector, capacity, comparer);
}
public static IObservable<IGroupedObservable<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, int capacity, IEqualityComparer<TKey> comparer)
{
return new GroupByObservable<TSource, TKey, TElement>(source, keySelector, elementSelector, capacity, comparer);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f4c9428bf00006d408fcfe4c514ee798
timeCreated: 1455373902
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using UniRx.Operators;
namespace UniRx
{
// Timer, Interval, etc...
public static partial class Observable
{
public static IObservable<long> Interval(TimeSpan period)
{
return new TimerObservable(period, period, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<long> Interval(TimeSpan period, IScheduler scheduler)
{
return new TimerObservable(period, period, scheduler);
}
public static IObservable<long> Timer(TimeSpan dueTime)
{
return new TimerObservable(dueTime, null, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<long> Timer(DateTimeOffset dueTime)
{
return new TimerObservable(dueTime, null, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<long> Timer(TimeSpan dueTime, TimeSpan period)
{
return new TimerObservable(dueTime, period, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<long> Timer(DateTimeOffset dueTime, TimeSpan period)
{
return new TimerObservable(dueTime, period, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<long> Timer(TimeSpan dueTime, IScheduler scheduler)
{
return new TimerObservable(dueTime, null, scheduler);
}
public static IObservable<long> Timer(DateTimeOffset dueTime, IScheduler scheduler)
{
return new TimerObservable(dueTime, null, scheduler);
}
public static IObservable<long> Timer(TimeSpan dueTime, TimeSpan period, IScheduler scheduler)
{
return new TimerObservable(dueTime, period, scheduler);
}
public static IObservable<long> Timer(DateTimeOffset dueTime, TimeSpan period, IScheduler scheduler)
{
return new TimerObservable(dueTime, period, scheduler);
}
public static IObservable<Timestamped<TSource>> Timestamp<TSource>(this IObservable<TSource> source)
{
return Timestamp<TSource>(source, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<Timestamped<TSource>> Timestamp<TSource>(this IObservable<TSource> source, IScheduler scheduler)
{
return new TimestampObservable<TSource>(source, scheduler);
}
public static IObservable<UniRx.TimeInterval<TSource>> TimeInterval<TSource>(this IObservable<TSource> source)
{
return TimeInterval(source, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<UniRx.TimeInterval<TSource>> TimeInterval<TSource>(this IObservable<TSource> source, IScheduler scheduler)
{
return new UniRx.Operators.TimeIntervalObservable<TSource>(source, scheduler);
}
public static IObservable<T> Delay<T>(this IObservable<T> source, TimeSpan dueTime)
{
return source.Delay(dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<TSource> Delay<TSource>(this IObservable<TSource> source, TimeSpan dueTime, IScheduler scheduler)
{
return new DelayObservable<TSource>(source, dueTime, scheduler);
}
public static IObservable<T> Sample<T>(this IObservable<T> source, TimeSpan interval)
{
return source.Sample(interval, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> Sample<T>(this IObservable<T> source, TimeSpan interval, IScheduler scheduler)
{
return new SampleObservable<T>(source, interval, scheduler);
}
public static IObservable<TSource> Throttle<TSource>(this IObservable<TSource> source, TimeSpan dueTime)
{
return source.Throttle(dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<TSource> Throttle<TSource>(this IObservable<TSource> source, TimeSpan dueTime, IScheduler scheduler)
{
return new ThrottleObservable<TSource>(source, dueTime, scheduler);
}
public static IObservable<TSource> ThrottleFirst<TSource>(this IObservable<TSource> source, TimeSpan dueTime)
{
return source.ThrottleFirst(dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<TSource> ThrottleFirst<TSource>(this IObservable<TSource> source, TimeSpan dueTime, IScheduler scheduler)
{
return new ThrottleFirstObservable<TSource>(source, dueTime, scheduler);
}
public static IObservable<T> Timeout<T>(this IObservable<T> source, TimeSpan dueTime)
{
return source.Timeout(dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> Timeout<T>(this IObservable<T> source, TimeSpan dueTime, IScheduler scheduler)
{
return new TimeoutObservable<T>(source, dueTime, scheduler);
}
public static IObservable<T> Timeout<T>(this IObservable<T> source, DateTimeOffset dueTime)
{
return source.Timeout(dueTime, Scheduler.DefaultSchedulers.TimeBasedOperations);
}
public static IObservable<T> Timeout<T>(this IObservable<T> source, DateTimeOffset dueTime, IScheduler scheduler)
{
return new TimeoutObservable<T>(source, dueTime, scheduler);
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7da89fcf95f5c364ca62bbb874005d32
timeCreated: 1455373899
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,292 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UniRx.InternalUtil;
using UniRx.Operators;
namespace UniRx
{
// Standard Query Operators
// onNext implementation guide. enclose otherFunc but onNext is not catch.
// try{ otherFunc(); } catch { onError() }
// onNext();
public static partial class Observable
{
static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1); // from .NET 4.5
public static IObservable<TR> Select<T, TR>(this IObservable<T> source, Func<T, TR> selector)
{
// sometimes cause "which no ahead of time (AOT) code was generated." on IL2CPP...
//var select = source as ISelect<T>;
//if (select != null)
//{
// return select.CombineSelector(selector);
//}
// optimized path
var whereObservable = source as UniRx.Operators.WhereObservable<T>;
if (whereObservable != null)
{
return whereObservable.CombineSelector<TR>(selector);
}
return new SelectObservable<T, TR>(source, selector);
}
public static IObservable<TR> Select<T, TR>(this IObservable<T> source, Func<T, int, TR> selector)
{
return new SelectObservable<T, TR>(source, selector);
}
public static IObservable<T> Where<T>(this IObservable<T> source, Func<T, bool> predicate)
{
// optimized path
var whereObservable = source as UniRx.Operators.WhereObservable<T>;
if (whereObservable != null)
{
return whereObservable.CombinePredicate(predicate);
}
var selectObservable = source as UniRx.Operators.ISelect<T>;
if (selectObservable != null)
{
return selectObservable.CombinePredicate(predicate);
}
return new WhereObservable<T>(source, predicate);
}
public static IObservable<T> Where<T>(this IObservable<T> source, Func<T, int, bool> predicate)
{
return new WhereObservable<T>(source, predicate);
}
/// <summary>
/// Lightweight SelectMany for Single Async Operation.
/// </summary>
public static IObservable<TR> ContinueWith<T, TR>(this IObservable<T> source, IObservable<TR> other)
{
return ContinueWith(source, _ => other);
}
/// <summary>
/// Lightweight SelectMany for Single Async Operation.
/// </summary>
public static IObservable<TR> ContinueWith<T, TR>(this IObservable<T> source, Func<T, IObservable<TR>> selector)
{
return new ContinueWithObservable<T, TR>(source, selector);
}
public static IObservable<TR> SelectMany<T, TR>(this IObservable<T> source, IObservable<TR> other)
{
return SelectMany(source, _ => other);
}
public static IObservable<TR> SelectMany<T, TR>(this IObservable<T> source, Func<T, IObservable<TR>> selector)
{
return new SelectManyObservable<T, TR>(source, selector);
}
public static IObservable<TResult> SelectMany<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, IObservable<TResult>> selector)
{
return new SelectManyObservable<TSource, TResult>(source, selector);
}
public static IObservable<TR> SelectMany<T, TC, TR>(this IObservable<T> source, Func<T, IObservable<TC>> collectionSelector, Func<T, TC, TR> resultSelector)
{
return new SelectManyObservable<T, TC, TR>(source, collectionSelector, resultSelector);
}
public static IObservable<TResult> SelectMany<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, int, IObservable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector)
{
return new SelectManyObservable<TSource, TCollection, TResult>(source, collectionSelector, resultSelector);
}
public static IObservable<TResult> SelectMany<TSource, TResult>(this IObservable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
{
return new SelectManyObservable<TSource, TResult>(source, selector);
}
public static IObservable<TResult> SelectMany<TSource, TResult>(this IObservable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
{
return new SelectManyObservable<TSource, TResult>(source, selector);
}
public static IObservable<TResult> SelectMany<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
{
return new SelectManyObservable<TSource, TCollection, TResult>(source, collectionSelector, resultSelector);
}
public static IObservable<TResult> SelectMany<TSource, TCollection, TResult>(this IObservable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector)
{
return new SelectManyObservable<TSource, TCollection, TResult>(source, collectionSelector, resultSelector);
}
public static IObservable<T[]> ToArray<T>(this IObservable<T> source)
{
return new ToArrayObservable<T>(source);
}
public static IObservable<IList<T>> ToList<T>(this IObservable<T> source)
{
return new ToListObservable<T>(source);
}
public static IObservable<T> Do<T>(this IObservable<T> source, IObserver<T> observer)
{
return new DoObserverObservable<T>(source, observer);
}
public static IObservable<T> Do<T>(this IObservable<T> source, Action<T> onNext)
{
return new DoObservable<T>(source, onNext, Stubs.Throw, Stubs.Nop);
}
public static IObservable<T> Do<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError)
{
return new DoObservable<T>(source, onNext, onError, Stubs.Nop);
}
public static IObservable<T> Do<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted)
{
return new DoObservable<T>(source, onNext, Stubs.Throw, onCompleted);
}
public static IObservable<T> Do<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
return new DoObservable<T>(source, onNext, onError, onCompleted);
}
public static IObservable<T> DoOnError<T>(this IObservable<T> source, Action<Exception> onError)
{
return new DoOnErrorObservable<T>(source, onError);
}
public static IObservable<T> DoOnCompleted<T>(this IObservable<T> source, Action onCompleted)
{
return new DoOnCompletedObservable<T>(source, onCompleted);
}
public static IObservable<T> DoOnTerminate<T>(this IObservable<T> source, Action onTerminate)
{
return new DoOnTerminateObservable<T>(source, onTerminate);
}
public static IObservable<T> DoOnSubscribe<T>(this IObservable<T> source, Action onSubscribe)
{
return new DoOnSubscribeObservable<T>(source, onSubscribe);
}
public static IObservable<T> DoOnCancel<T>(this IObservable<T> source, Action onCancel)
{
return new DoOnCancelObservable<T>(source, onCancel);
}
public static IObservable<Notification<T>> Materialize<T>(this IObservable<T> source)
{
return new MaterializeObservable<T>(source);
}
public static IObservable<T> Dematerialize<T>(this IObservable<Notification<T>> source)
{
return new DematerializeObservable<T>(source);
}
public static IObservable<T> DefaultIfEmpty<T>(this IObservable<T> source)
{
return new DefaultIfEmptyObservable<T>(source, default(T));
}
public static IObservable<T> DefaultIfEmpty<T>(this IObservable<T> source, T defaultValue)
{
return new DefaultIfEmptyObservable<T>(source, defaultValue);
}
public static IObservable<TSource> Distinct<TSource>(this IObservable<TSource> source)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<TSource>();
#else
var comparer = EqualityComparer<TSource>.Default;
#endif
return new DistinctObservable<TSource>(source, comparer);
}
public static IObservable<TSource> Distinct<TSource>(this IObservable<TSource> source, IEqualityComparer<TSource> comparer)
{
return new DistinctObservable<TSource>(source, comparer);
}
public static IObservable<TSource> Distinct<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<TKey>();
#else
var comparer = EqualityComparer<TKey>.Default;
#endif
return new DistinctObservable<TSource, TKey>(source, keySelector, comparer);
}
public static IObservable<TSource> Distinct<TSource, TKey>(this IObservable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
return new DistinctObservable<TSource, TKey>(source, keySelector, comparer);
}
public static IObservable<T> DistinctUntilChanged<T>(this IObservable<T> source)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<T>();
#else
var comparer = EqualityComparer<T>.Default;
#endif
return new DistinctUntilChangedObservable<T>(source, comparer);
}
public static IObservable<T> DistinctUntilChanged<T>(this IObservable<T> source, IEqualityComparer<T> comparer)
{
if (source == null) throw new ArgumentNullException("source");
return new DistinctUntilChangedObservable<T>(source, comparer);
}
public static IObservable<T> DistinctUntilChanged<T, TKey>(this IObservable<T> source, Func<T, TKey> keySelector)
{
#if !UniRxLibrary
var comparer = UnityEqualityComparer.GetDefault<TKey>();
#else
var comparer = EqualityComparer<TKey>.Default;
#endif
return new DistinctUntilChangedObservable<T, TKey>(source, keySelector, comparer);
}
public static IObservable<T> DistinctUntilChanged<T, TKey>(this IObservable<T> source, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException("source");
return new DistinctUntilChangedObservable<T, TKey>(source, keySelector, comparer);
}
public static IObservable<T> IgnoreElements<T>(this IObservable<T> source)
{
return new IgnoreElementsObservable<T>(source);
}
public static IObservable<Unit> ForEachAsync<T>(this IObservable<T> source, Action<T> onNext)
{
return new ForEachAsyncObservable<T>(source, onNext);
}
public static IObservable<Unit> ForEachAsync<T>(this IObservable<T> source, Action<T, int> onNext)
{
return new ForEachAsyncObservable<T>(source, onNext);
}
}
}

Some files were not shown because too many files have changed in this diff Show More