본문 바로가기

게임개발/UniRx

[UniRx Operator] Buffer, Pairwise

 

 

 

Buffer(count = x)

 

 

발생한 이벤트를 x개씩 모아서 통지한다.

 

 

 

 

더보기
using UnityEngine;
using UniRx;

public class Game : MonoBehaviour
{
    IntReactiveProperty _property = new IntReactiveProperty();

    void Start()
    {
        _property
            .Buffer(2)
            .Subscribe(values => Debug.Log($"({values[0]}, {values[1]})"));     // X

        _property.Value = 1;        // 이벤트 통지: (0, 1)

        _property.Value = 2;        // X

        _property.Value = 3;        // 이벤트 통지: (2, 3)
    }
}

 

 

Buffer(count = x, skip = y)

 

 

x개의 이벤트가 발생하면 모아서 통지하고, 그 다음 y개의 이벤트가 발생할때마다

 

가장 최근 이벤트 x개를 모아서 통지한다.

 

 

 

 

더보기
using UnityEngine;
using UniRx;

public class Game : MonoBehaviour
{
    IntReactiveProperty _property = new IntReactiveProperty();

    void Start()
    {
        _property
            .Buffer(2, 3)
            .Subscribe(values => Debug.Log($"({values[0]}, {values[1]})"));     // X

        _property.Value = 1;        // 이벤트 통지: (0, 1)

        _property.Value = 2;        // X

        _property.Value = 3;        // X

        _property.Value = 4;        // 이벤트 통지: (3, 4)
    }
}

 

 

Buffer(second = x)

 

 

x초동안 발생한 이벤트를 모아서 통지한다. (이벤트 구독후 x초마다 통지된다.)

 

 

 

 

더보기
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;

public class Game : MonoBehaviour
{
    IntReactiveProperty _property = new IntReactiveProperty();

    IEnumerator Start()
    {
        _property
            .Buffer(TimeSpan.FromSeconds(1f))
            .Subscribe(values => LogValues(values));    // 이벤트 구독 후 매초 이벤트 통지

        yield return new WaitForSeconds(0.5f);

        _property.Value = 1;

        yield return new WaitForSeconds(0.5f);      // 1초후 이벤트 통지: 0, 1

        yield return new WaitForSeconds(0.5f);

        _property.Value = 2;

        yield return new WaitForSeconds(0.5f);      // 2초후 이벤트 통지: 2

        _property.Value = 3;

        _property.Value = 4;

        yield return new WaitForSeconds(0.5f);

        _property.Value = 5;

        yield return new WaitForSeconds(0.5f);      // 3초후 이벤트 통지: 3, 4, 5
    }

    void LogValues(IList<int> values)
    {
        foreach (var v in values)
        {
            Debug.Log(v);
        }
    }
}

 

 

Pairwise


 

Buffer(count = 2, skip = 1)과 동일하다.

 

상태 변화를 체크할때 유용하다.

 

 

 

 

더보기
using UnityEngine;
using UniRx;

public class Game : MonoBehaviour
{
    IntReactiveProperty _property = new IntReactiveProperty();

    void Start()
    {
        _property
            .Pairwise()
            .Subscribe(value => Debug.Log($"{value.Previous} -> {value.Current}"));

        _property.Value = 1;        // 이벤트 통지: 0 -> 1

        _property.Value = 2;        // 이벤트 통지: 1 -> 2

        _property.Value = 1;        // 이벤트 통지: 2 -> 1
    }
}