Search code examples
c#unity-game-engineunirx

Can one Observable() handle the Subscribe for two situations?


I'm applying reactive programming to the Unity3D project.

Entering a character in InputField enables the button and disables it if there are no characters. Can this logic be processed in one stream using UniRx.Observable?

inputID.OnValueChangedAsObservable()
            .Where(x => string.IsNullOrEmpty(x) == false)
            .Subscribe(_ => buttonLogin.gameObject.SetActive(true));

inputID.OnValueChangedAsObservable()
            .Where(x => string.IsNullOrEmpty(x) == true)
            .Subscribe(_ => buttonLogin.gameObject.SetActive(false));

Can combine these two logics into one logic?

Please reply. Thank you.


Solution

  • Yes, you can use the Map operator.

    http://reactivex.io/documentation/operators/map.html

    "transform the items emitted by an Observable by applying a function to each item"

    Replace Where with Map, and inside the map operator, you'll be passed your x variable, and return the boolean from your IsNullOrEmpty check. That boolean will be passed in as a variable in your subscription which you can use directly in setActive.