0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ただただC#でReactive Extensions(Rx)を使ってみる ~周期処理~

Posted at

はじめに

本記事はRx初学者の筆者がRxをただただ使ってみて学びや気づきをまとめたものです。
なお、本記事はこちらの記事の続編の位置づけです。

周期処理を使ってみる

前回に引き続き、今回はRxを使って周期処理を実現してみます。
以下に例を示します。

周期処理で現在時刻を表示する時計を作成する例

以下のように1秒ごとに現在時刻を更新して表示する時計のようなサンプルを考えます。
アプリケーション動作.gif
このサンプルは、Rxを使って1秒間隔の周期処理を定義して、その周期処理の中でテキストブロックの内容を現在時刻に更新し続けることで実現しています。
具体的なMainWindow.xamlとコードビハインドのMainWindow.xaml.csは以下です。(サンプルとしての説明をしやすくするためにコードビハインドに記載をしています。MVVMに従った作り方になっていないためご承知ください。)

  • MainWindow.xaml
<Window x:Class="RxTimerSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="75" Width="150"
        Loaded="MainWindow_OnLoaded">
    <Grid>
        <!-- 現在時刻を表現するテキストブロック -->
        <TextBlock x:Name="currentTimeTextBlock"/>
    </Grid>
</Window>
  • MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    #region コンストラクタ

    /// <summary>
    /// コンストラクタ
    /// </summary>
    public MainWindow()
    {
        InitializeComponent();
    }

    #endregion

    #region イベントハンドラ

    /// <summary>
    /// ウィンドウロード時のイベントハンドラ
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        // 周期処理の登録後から周期の計測を始めるまでのインターバル
        // この例では即時で計測開始としている
        var dueTime = TimeSpan.FromSeconds(0);

        // 周期
        // ここで設定した周期の間隔で処理を実行する
        // この例では周期は1秒としている
        var period = TimeSpan.FromSeconds(1);

        // 周期処理の設定
        Observable.Timer(dueTime, period)
            .Subscribe(_ =>
            {
                // 毎周期で行う処理
                // 以下はxamlで定義したテキストブロックの表示内容をその時点での現在時刻に更新する
                Dispatcher.Invoke(() => currentTimeTextBlock.Text = DateTime.Now.ToString());
            });
    }

    #endregion

}

大事なポイントはMainWindow.xaml.csのMainWindow_OnLoadedメソッドの部分です。
Observable.Timerメソッドを使って、周期処理の設定をしています。周期の計測を始めるまでのインターバル(変数dueTime)と周期(変数period)を指定したうえで、Subscribeメソッド内で周期処理の実処理を登録します。
上記のコードの場合は、インターバルは0秒、周期は1秒、実処理ではMainWindow.xamlで定義したテキストブロックの表示内容を現在時刻に更新しています。
これによって1秒ごとにテキストブロックの内容が現在時刻に更新されるので、サンプルが実現できています。
上記のように手軽に周期処理が実現できる点が良い点だなと個人的に思いました。

さいごに

今回はRxを使って周期処理を実現してみました。
手軽に周期処理を実現できる点が良い点だなと思いました。
Rxでできることはまだまだたくさんあるため、今後もRxを使って、理解した内容を技術記事としてアウトプットしていこうと思います。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?