LoginSignup
41
23

More than 5 years have passed since last update.

【UniRx】ReactivePropertyの初期値のプッシュを無視したいとき

Last updated at Posted at 2017-09-23

参考記事

Unityにおけるコルーチンの省メモリと高速化について、或いはUniRx 5.3.0でのその反映

初期値がプッシュされる例

初期値がプッシュされる例
using UnityEngine;
using UniRx;


public class Example : MonoBehaviour
{
    private readonly IntReactiveProperty _count = new IntReactiveProperty();

    private void Start()
    {
        _count
            .Subscribe(count => Debug.Log(count))
            .AddTo(gameObject);

        _count.Value = 1;
    }
}
出力結果

ss1.PNG

初期値がプッシュされないSkipLatestValueOnSubscribeを利用する例

初期値がプッシュされないSkipLatestValueOnSubscribeを利用する例
using UnityEngine;
using UniRx;


public class Example : MonoBehaviour
{
    private readonly IntReactiveProperty _count = new IntReactiveProperty();

    private void Start()
    {
        _count
            .SkipLatestValueOnSubscribe()
            .Subscribe(count => Debug.Log(count))
            .AddTo(gameObject);

        _count.Value = 1;
    }
}
出力結果

ss2.PNG

SkipLatestValueOnSubscribeの実装

SkipLatestValueOnSubscribeの実装
public static IObservable<T> SkipLatestValueOnSubscribe<T>(this IReadOnlyReactiveProperty<T> source)
{
    return source.HasValue ? source.Skip(1) : source;
}

まとめ

Rx.NET用のReactivePropertyでは、コンストラクタでReactiveProeprtyModeとして
None | RaiseLatestValueOnSubscribe | DistinctUntilChanged を指定できるようなデザインを選んでいるのですが
(というのも、Viewにデータバインディングするため構築時の初期値はnullであることが確定しているという
シチュエーションが割とあるため)
UniRxのReactivePropertyではSubscribe側が選ぶというデザインにしています。

UniRxにはSubscribeToTextSubscribeToInteractableなど
流れるように記述可能な拡張メソッドが定義されていて素晴しいですね。

41
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
23