0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AndroidにおけるRemoteConfig用Repository実装

Posted at

はじめに

今回はAndroid実装におけるRemoteConfigの実装をしていきます

コード

@Singleton
class RemoteConfigRepository @Inject constructor(
    @ApplicationContext private val context: Context,
) {
    private val remoteConfig: FirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
    private var listenerRegistration: ConfigUpdateListenerRegistration? = null

    init {
        // Remote Configの設定
        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = 3600
        }
        remoteConfig.setConfigSettingsAsync(configSettings)
    }

    /**
     * Remote Configの値を取得して有効化する
     */
    suspend fun fetch(): Result<Unit, Exception> = withContext(Dispatchers.IO) {
        try {
            remoteConfig.fetchAndActivate().await()
            Timber.d("Remote Config fetch and activate succeeded")
            Result.Success(Unit)
        } catch (e: Exception) {
            Timber.e(e, "Remote Config fetch and activate failed")
            Result.Error(e)
        }
    }

    /**
     * 文字列値を取得
     */
    fun getString(key: String): String {
        return remoteConfig.getString(key)
    }

    /**
     * Boolean値を取得
     */
    fun getBoolean(key: String): Boolean {
        return remoteConfig.getBoolean(key)
    }

    /**
     * Long値を取得
     */
    fun getLong(key: String): Long {
        return remoteConfig.getLong(key)
    }

    /**
     * Double値を取得
     */
    fun getDouble(key: String): Double {
        return remoteConfig.getDouble(key)
    }

    /**
     * カスタムシグナル(ユーザープロパティ)を設定
     *
     * Firebase Remote Configの条件でこのプロパティを参照して、
     * 特定のユーザーにのみ特定の値を返すことができます。
     *
     * @param key プロパティ名
     * @param value プロパティ値(nullの場合はプロパティを削除)
     *
     */
    fun setUserProperty(key: String, value: String?) {
        Firebase.analytics.setUserProperty(key, value)
        Timber.d("User property set: $key = $value")
    }

    /**
     * リアルタイム更新のリスナーを開始
     *
     * Firebase Consoleで設定が変更されたときに自動的に最新の値を取得して有効化します。
     * アプリ起動時に一度だけ呼び出してください。
     */
    fun startListening() {
        if (listenerRegistration != null) {
            Timber.d("Remote Config listener already started")
            return
        }

        listenerRegistration = remoteConfig.addOnConfigUpdateListener(
            object : ConfigUpdateListener {
                override fun onUpdate(configUpdate: ConfigUpdate) {
                    Timber.d("Remote Config updated. Updated keys: ${configUpdate.updatedKeys}")
                    // 更新された設定を有効化
                    remoteConfig.activate().addOnCompleteListener { task ->
                        if (task.isSuccessful) {
                            Timber.d("Remote Config activated successfully")
                        } else {
                            Timber.e(task.exception, "Remote Config activation failed")
                        }
                    }
                }

                override fun onError(error: FirebaseRemoteConfigException) {
                    Timber.e(error, "Remote Config update listener error")
                }
            },
        )
        Timber.d("Remote Config listener started")
    }

    /**
     * リアルタイム更新のリスナーを停止
     *
     * 通常は呼び出す必要はありませんが、テストやメモリリーク対策で必要な場合に使用します。
     */
    fun stopListening() {
        listenerRegistration?.remove()
        listenerRegistration = null
        Timber.d("Remote Config listener stopped")
    }
}

最後に

リアルタイムで変数を制御できるので結構有用ですよね

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?