LoginSignup
8
8

More than 5 years have passed since last update.

C# + ReactiveProperty vs Kotlin + RxProperty : Command 編

Posted at

ボタンを押したら、数値が1ずつ加算されていく、というやつの ViewModel 側

C# + ReactiveProperty の場合

Counter がラベルにバインドする数値、 Increment がボタンにバインドするコマンド。

public class MainViewModel
{
    public ReactiveProperty<int> Counter { get; } = new ReactiveProperty<int>(0);
    public ReactiveCommand Increment { get; } 

    public MainViewModel()
    {
        // Increment コマンドは、 Counter が 10 未満の間、使用可能
        Increment = Counter.Select(x => x < 10).ToReactiveCommand();
        // Increment コマンドが実行されたら Counter を +1 してく
        Increment.Subscribe(x => Counter.Value = Counter.Value + 1);
    }
}

Kotlin + RxProperty の場合

counter がラベルにバインドする数値、 increment がボタンにバインドするコマンド。

class MainViewModel {
    val counter = RxProperty<Int>(0)

    // Increment コマンドは、 Counter が 10 未満の間、使用可能
    val increment = RxCommand<Unit>(counter.map { it < 10 }).apply {
        // Increment コマンドが実行されたら Counter を +1 してく
        this.subscribe({ counter.set(counter.get()!! + 1) })
    }
}

C# は言語の仕様?で、読み取り専用プロパティの定義のなかで他のプロパティを参照できない。のでコンストラクタに書く。

Kotlin はその辺のしがらみが少ないので、思った通りに書ける感じ。
さらに .apply 関数で Command の subscribe 処理も定義できるので、結果コンストラクタに書くことがなくなりました、スッキリ。

Android + Kotlin な人は、 RxProperty もっと使っていきましょー

コードの短さだと Kotlin だし、この C# の MainViewModel.cs は、Xamarin(Android, iOS, Mac) や Windows など全部共通実装でいけちゃう。

どちらも良い。

8
8
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
8
8