我有一个简单的视图模型类,它的状态正在被一个函数修改
@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,我想绘制一条正在使用MapState
的coords
字段构建的折线。
我正在前台服务中获取当前位置更新,该前台服务从可以访问viewModel
的主活动类启动
class MainActivity : ComponentActivity() {
private val viewModel: MapViewModel by viewModels()
// ...
但我无法在服务中获取viewModel
的引用。
每当服务获取新位置时,如何更新viewModel
的状态?
1条答案
按热度按时间eaf3rand1#
你可以使用LiveData,例如在一个单独的文件
object LocationLiveData : LiveData<Location>()
中定义一个LiveData对象,然后在你的服务中,每当你得到一个新的位置时,更新LocationLiveData的值并在视图模型中观察LocationLiveData并更新视图模型的状态