如何将实时变化的数据从activity传递到fragment?

Do *_* Ji 0 android kotlin android-bluetooth android-runonuithread

我目前正在从蓝牙传感器读取数据,因此数据会实时变化并且不断变化。我已将数据存储在变量中:liveData:ByteArray

现在我尝试将 liveData 从 MainActivity 发送到 Sensordisplayfragment。

更新

根据@CTD的评论,这就是我尝试过的,不幸的是我对viewModel没有太多了解,而且在线研究很混乱,因为似乎有很多方法来实现viewModel。

在我存储变量 liveData 的 MainActivity 类中:

val model:MyViewModel by viewModels()
    private fun processLiveData(liveData : ByteArray){
        livedata = liveData
        model.uploadData(livedata)
    }
Run Code Online (Sandbox Code Playgroud)

在 MyViewModel.class 中,viewModel 位于:

class MyViewModel: ViewModel() {
    private val realtimedata = MutableLiveData<ByteArray>()

    fun uploadData(data:ByteArray){
        realtimedata.value = data
    }

    fun loadData():LiveData<ByteArray>{
        return realtimedata
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,在我获取数据的 Sensordisplay 片段中:

val 模型:MyViewModel by viewModels()

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    model.loadData().observe(viewLifecycleOwner,Observer<ByteArray>{
        passandprocessLiveData(it)
    })
    return inflater.inflate(R.layout.sensordisplay, container, false)
}

override fun onResume(){
    activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    model.loadData().observe(viewLifecycleOwner,Observer<ByteArray>{
        passandprocessLiveData(it)
    })
    super.onResume()
}

fun passandprocessLiveData(data:Bytearray){
    //extract information from data and make 
    //cardviews move in realtime according to the extracted data
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,没有任何内容被传输,我的卡片视图也没有移动。我可以保证cardview代码的移动没有​​错误。有人可以建议我可以添加什么吗?显然我需要使用一个 init() 函数。

CTD*_*CTD 8

class MyViewModel : ViewModel() {
    private val realtimedata = MutableLiveData<ByteArray>()

    val sensorData: LiveData<ByteArray> = realtimedata

    fun update(data: ByteArray){
        realtimedata.value = data
    }
}

class MainActivity: Activity() {

    private val viewModel: MyViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        bluetoothSensorCallBack { data ->
            // Update the realtimedata 
            viewModel.update(data)
        }
    }
}

class SensordisplayFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: MyViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.sensorData.observe(viewLifecycleOwner, Observer<ByteArray> { data ->
            // Update the UI
        })
    }
}
Run Code Online (Sandbox Code Playgroud)