Firebase 远程配置 - 检查值是否存在

Firebase Remote Config - check if value exists

我想在我的应用程序中为某些布尔值实现某种代理。逻辑如下:

  1. 我从后端收到一组值
  2. 我也在 Firebase 中设置了其中一些值
  3. 在应用程序中使用值时,我首先检查它是否存在于 Firebase 中

    3.1。如果存在,取 Firebase 值

    3.2。如果不存在,则取后端值

问题是 - 如何检查该值是否存在于 Firebase 远程配置中?

Remote Config 已经这样做了,如 documentation. You're obliged to provide default values for parameters that haven't been defined in the console. They work exactly as you describe, without having to do any extra work. These defaults will be used until you perform a fetch 中所述。如果该值是在控制台中定义的,那么将使用它而不是默认值。

我找到了解决方案:

Firebase Remote Config 获取所有值作为 Strings,然后才将它们映射到便利方法中的其他类型,例如 getBoolean()getLong()

因此,可以按如下方式检查布尔配置值是否存在:

String value = firebaseRemoteConfig.getString("someKey");

if(value.equals("true")){
    //The value exists and the value is true
} else if(value.equals("false")) {
    //The value exists and the value is false
} else if(value.equals("")) {
    //The value is not set in Firebase
}

其他类型也是如此,即在 firebase 上设置为 64 的 long 值将从 getString() 返回为 "64"

我找到了另一种方法,也许对登陆这里的其他人有用:

val rawValue = remoteConfig.getValue(key)
val exists = rawValue.source == FirebaseRemoteConfig.VALUE_SOURCE_REMOTE

在这种情况下,仅当值是从远程返回的(并且尚未设置为默认值或静态提供值)时,exists 才为真。接受的答案很容易出错,因为没有考虑空字符串是从 remote

返回的有效字符串的情况

这里是 FirebaseRemoteConfigValue

的文档

Firebase 远程配置 (FRC),实际上提供了 3 个常量以了解使用 getValue(forKey) (documentation)

检索的值从何处获取
  • VALUE_SOURCE_DEFAULT --> 用户默认设置的值
  • VALUE_SOURCE_REMOTE --> 来自远程服务器的值
  • VALUE_SOURCE_STATIC --> 返回值为默认值(FRC 没有密钥)

知道了这一点,你可以像这样做一个“包装器”:

class FirebaseRemoteConfigManager {
.....

    override fun getBoolean(forKey: String): Boolean? = getRawValue(forKey)?.asBoolean()

    override fun getString(forKey: String): String? = getRawValue(forKey)?.asString()

    override fun getDouble(forKey: String): Double? = getRawValue(forKey)?.asDouble()

    override fun getLong(forKey: String): Long? = getRawValue(forKey)?.asLong()

    private fun getRawValue(forKey: String): FirebaseRemoteConfigValue? {
        val rawValue = remoteConfig.getValue(forKey)
        return if (rawValue.source == FirebaseRemoteConfig.VALUE_SOURCE_STATIC) null else rawValue
    }
...
}

如果你得到 null,你就知道密钥不存在于 FRC 中。 注意使用默认值作为“不存在”,因为也许在你的 FRC 中你想设置这个值,你会得到一个误报