LoginSignup
47
36

More than 3 years have passed since last update.

UniRxの「Debug」オペレータが便利

Posted at

「Debug」オペレータ

UniRxには「Debug」という便利なオペレータが存在します。
これは「Observable上で起きたすべてのイベントをログに出力する」というオペレータです。

  • どの値が発行されたか
  • 何の例外が起きたか
  • どのタイミングでSubscribe()されたか
  • どのタイミングで購読が中断されたか

などをこのオペレータ1つですべて知ることができます。

定義

定義としてはこうなってます。

// copy from https://github.com/neuecc/UniRx/blob/master/Assets/Plugins/UniRx/Scripts/UnityEngineBridge/Diagnostics/ObservableDebugExtensions.cs
public static IObservable<T> Debug<T>(this IObservable<T> source, string label = null)
{
#if DEBUG
    var l = (label == null) ? "" : "[" + label + "]";
    return source.Materialize()
        .Do(x => UnityEngine.Debug.Log(l + x.ToString()))
        .Dematerialize()
        .DoOnCancel(() => UnityEngine.Debug.Log(l + "OnCancel"))
        .DoOnSubscribe(() => UnityEngine.Debug.Log(l + "OnSubscribe"));

#else
    return source;
#endif
}

public static IObservable<T> Debug<T>(this IObservable<T> source, UniRx.Diagnostics.Logger logger)
{
#if DEBUG
    return source.Materialize()
        .Do(x => logger.Debug(x.ToString()))
        .Dematerialize()
        .DoOnCancel(() => logger.Debug("OnCancel"))
        .DoOnSubscribe(() => logger.Debug("OnSubscribe"));

#else
    return source;
#endif
}

Do() + DoOnCancel() + DoOnSubscribe() ということで、Observable上で起きたすべてのイベントをログへ出力できるようになっています。
しかもラベルを付与したり、UniRx.Diagnostics.Loggerを利用することもできます。

ちなみにUniRx.Diagnostics名前空間に定義されているのでこちらへのusingを忘れずに。

使い方

Observableの途中にDebug()を挟むだけです。

using UniRx;
using UniRx.Diagnostics;
using UnityEngine;

public sealed class DebugSample : MonoBehaviour
{
    private readonly Subject<int> _subject = new Subject<int>();

    private void Start()
    {
        _subject
            .Debug("Debugサンプル") // Debugオペレータ
            .Subscribe()
            .AddTo(this);

        _subject.OnNext(1);
        _subject.OnNext(2);
        _subject.OnNext(3);

        Destroy(gameObject);
    }

    private void OnDestroy()
    {
        _subject.Dispose();
    }
}
実行結果
[Debugサンプル]OnSubscribe
[Debugサンプル]OnNext(1)
[Debugサンプル]OnNext(2)
[Debugサンプル]OnNext(3)
[Debugサンプル]OnCancel

ログの読み方

メッセージ 意味
OnSubscribe ObservableSubscribe()された
OnNext(Value) Valueという値のOnNextメッセージが発行された
OnCompleted OnCompletedメッセージが発行された
OnError(ex) exという型のOnErrorメッセージが発行された
OnCancel Subscribe()Dispose()が実行された

最後に

UniRxについて学べる技術書が出版されました。

image.png

(ちなみにこのDebugオペレータについて、本の中で解説するのを忘れています。本当にすいません…。)

47
36
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
47
36