UniRx: 購読をキャンセルする
IObservable<T>.Subscribe()
から返却される IDisposable
の Dispose()
を呼び出すと購読がキャンセルされます。
using System; using UniRx; using UnityEngine; public class Main : MonoBehaviour { private IDisposable _disposable; void Start() { var s = Observable.Interval(TimeSpan.FromSeconds(1)); _disposable = s.Subscribe(e => Debug.Log("e: " + e), () => Debug.Log("OnCompleted")); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("キャンセルします"); _disposable.Dispose(); } } }
実行結果です。
e: 0 e: 1 w: 2 キャンセルします。 // ←スペースキーを押した
Dispose()
を呼び出してキャンセルすると、それ以降のデータは通知されなくなります。