对于MVVM体系结构,需要在WebSocket
类中调用ViewModel
变量。
[我的WebSocket
服务在MainActivity
中声明。
因此,MainActivity
需要在ViewModel
中实例化。
我试图声明一个实例::'''(活动为MainActivity)'''在我的ViewModel类中,但这会引发错误。
class ComfortViewModel : ViewModel() {
private val comfortModel = ComfortModel()
val TFL: LiveData<Int>
get() = TFLS
val TFR: LiveData<Int>
get() = TFRS
val BSF: LiveData<Int>
get() = BSFS
/** liveData object access Model data **/
private val TFLS = MutableLiveData<Int>()
private val TFRS = MutableLiveData<Int>()
private val BSFS = MutableLiveData<Int>()
init {
TFLS.value = comfortModel.tempFrontLeft
} init {
TFRS.value = comfortModel.tempFrontRight
} init {
BSFS.value = comfortModel.blowerSpeedFront
}
/** onClicklisteners: Declaration done at the 'XML' file; logic is here.**/
private fun TIFL() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (TFL <= 29) {
(activity as MainActivity).mWebSocketService?.StepTemperature(
SignalIdentifier.HVAC_ROW1LEFTTEMPERATURE.name,
+1
)
}
}
}
private fun TDFL() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (TFL >= 1) {
(activity as MainActivity).mWebSocketService?.StepTemperature(
SignalIdentifier.HVAC_ROW1LEFTTEMPERATURE.name,
-1
)
}
}
}
private fun TIFR() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (TFR <= 29) {
(activity as MainActivity).mWebSocketService?.StepTemperature(
SignalIdentifier.HVAC_ROW1RIGHTTEMPERATURE.name,
+1
)
}
}
}
private fun TDFR() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (TFR >= 1) {
(activity as MainActivity).mWebSocketService?.StepTemperature(
SignalIdentifier.HVAC_ROW1RIGHTTEMPERATURE.name,
-1
)
}
}
}
private fun BDF() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (BSF >= 1) {
(activity as MainActivity).mWebSocketService?.StepBlowerSpeed(
SignalIdentifier.HVAC_ROW1LEFTBLOWER.name,
-1
)
}
}
}
private fun BIF() {
if ((activity as MainActivity).appInstalled(MainActivity.serverUri)) {
if (BSF <= 5) {
(activity as MainActivity).mWebSocketService?.StepBlowerSpeed(
SignalIdentifier.HVAC_ROW1LEFTBLOWER.name,
+1
)
}
}
}
}
我想我声明LiveData
变量的方式并不是最好的。我只想访问温度变量的静态数据(清单6。但是MutableLiveData<List<Int>>
并没有真正解决。
[还请提出其他建议,使我的ViewModel
和WebSocket彼此对话。
提前感谢。
您有两个大错误
1-在活动或片段中声明Web Web套接字其视图模型中的两用活动
解释概念:
1-您必须向Web套接字工具声明单独的类(创建实例,侦听,调用,连接和断开连接)以应用单一职责原则
2-在MVVM中,视图和视图模型之间的关系是一个方向视图,在内部视图模型中可观察到,但是视图模型不像MVP关系那样是对2个方向的视图的引用,因此您不应在侧视图模型中声明您的主要活动解决方案:
1-插座类
class SocketService{
companion object {val instance :SocketService}
fun connect()
fun disconnect()
fun sendMessage(invokeMethodName:String,data:JsonObject)
fun subscribe(listenMethodName:String,listner:Listner)
}
2-视图模型
val receiveMessageResponse = MutableLiveData<String>()
SocketService.instance!!.subscribe(RECEIVE_MESSAGE, HubEventListener {
receiveMessageResponse.postValue(it)
})
3-活动
viewModel.receiveMessageResponse.observe(this, Observer {
//use the received message here
})
结论:
socketService ------>视图模型---------->活动
活动