如何在Android应用中将数据从Service传递到HiltViewModel?

ryoqjall  于 2023-05-15  发布在  Android
关注(0)|答案(1)|浏览(294)

我有一个简单的视图模型类,它的状态正在被一个函数修改

@HiltViewModel
class MapViewModel @Inject constructor() : ViewModel() {

    fun addNewLocation(location: Location) {
        val latLng = LatLng(location.latitude, location.longitude);
        state.value.coords?.add(latLng)
        state.value = state.value.copy(
            lastKnownLocation = location
        )
    }

    val state: MutableState<MapState> = mutableStateOf(
        MapState(
            lastKnownLocation = null,
            coords = mutableListOf<LatLng>()
        )
    )
}

还有一个@Composable组件用于渲染Map,我想绘制一条正在使用MapStatecoords字段构建的折线。
我正在前台服务中获取当前位置更新,该前台服务从可以访问viewModel的主活动类启动

class MainActivity : ComponentActivity() {
      private val viewModel: MapViewModel by viewModels()
    // ...

但我无法在服务中获取viewModel的引用。
每当服务获取新位置时,如何更新viewModel的状态?

eaf3rand

eaf3rand1#

你可以使用LiveData,例如在一个单独的文件object LocationLiveData : LiveData<Location>()中定义一个LiveData对象,然后在你的服务中,每当你得到一个新的位置时,更新LocationLiveData的值

LocationLiveData.value = location

并在视图模型中观察LocationLiveData并更新视图模型的状态

LocationLiveData.observeForever { location ->
        addNewLocation(location)
    }

相关问题