1

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.

오명근
  • 15
  • 1
  • 4
  • 1
    No expert but can't you simply do `inputID.OnValueChangedAsObservable().Subscribe(s => buttonLogin.gameObject.SetActive(!string.IsNullOrEmpty(s)));`? – derHugo Sep 10 '19 at 17:01

1 Answers1

0

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.

Dan
  • 321
  • 3
  • 11
  • 1
    Seems like you could just skip the `Where` and have `.Subscribe(x => buttonLogin.gameObject.SetActive(string.IsNullOrEmpty(x))` - or is this not as straight-forward as it looks? – Corey Sep 10 '19 at 11:07
  • That would also work but you lose out on sought-after reactive fanciness. – Dan Sep 10 '19 at 11:19
  • Fancy is... nice I guess. But adding extra layers of complexity just so you can say "look how pretty this is" kinda sucks, doesn't it? I'm far more interested in what works *best* than what looks pretty. Except Expressions. They're sexy. – Corey Sep 10 '19 at 11:28