观察者何时需要实时数据?

问题描述 投票:0回答:1

我有一个视图模型,该模型将字节数组处理为稍微复杂的浮点数组。数据的一部分是时间戳,我已将其设置为LiveData类型,并且观察者侦听时间戳中的更改。发生更改时,它会获得新的时间戳记,并且还会获得浮点数数组。

我的问题是在LiveData对象中设置“值”时,观察者是否立即被调用,或者它是否等待周围的函数完成?换句话说,在设置“值”之前,我是否应该确保更新观察者正在访问的其他任何数据?

而且,这是否在滥用LiveData机制(将其用作更大数据更改的标志)?

  val mTime = MutableLiveData<Double>()
  var mStateDataSet = ArrayList<ArrayList<Float>>()

  fun updateData(rawData: ByteArray) {

    val buffer = ByteBuffer.wrap(rawData).order(ByteOrder.LITTLE_ENDIAN)

    val min = (buffer.getInt(4)).toDouble()
    val usec = (buffer.getInt(8)).toDouble()

    val time: Double = min * 60.0 + usec * (1.0 / 1e6)

    // Update the live data....
    mTime.value = time

    // This data is used by the observer of "mTime"
    mStateDataSet[KEY_VOLTAGES] = getSubDataFloat(buffer, NUM_VOLTAGE);
    mStateDataSet[KEY_PRESSURES] = getSubDataFloat(buffer, NUM_PRESSURE);
    mStateDataSet[KEY_LEFT_ANGLES] = getSubDataFloat(buffer, NUM_LEFT_ANGLES);
    mStateDataSet[KEY_RIGHT_ANGLES] = getSubDataFloat(buffer, NUM_RIGHT_ANGLES);
    mStateDataSet[KEY_LEFT_ACCEL] = getSubDataFloat(buffer, NUM_LEFT_ACCEL);
    mStateDataSet[KEY_RIGHT_ACCEL] = getSubDataFloat(buffer, NUM_RIGHT_ACCEL);
    mStateDataSet[KEY_DEBUG] = getSubDataFloat(buffer, NUM_DEBUG);

  }

// Example observer from one of my fragments
    val timeObserver = Observer<Double> { newTime ->
      addDataPoint(mSharedStateDataViewModel.mStateDataSet, newTime)
    }
    mSharedStateDataViewModel.mTime.observe(viewLifecycleOwner, timeObserver)
android kotlin android-livedata
1个回答
0
投票

您应使用以下命令更新实时数据值

mTime.postValue(time)
© www.soinside.com 2019 - 2024. All rights reserved.