Search code examples
androidandroid-studiokotlinmvvmviewmodel

Calling Mainactivity inside Viewmodel(updated)


For the MVVM architecture, need to call a WebSocket variable in the ViewModel class.

And my WebSocket service is declared in the MainActivity.

So, MainActivity needs to be instantiated in the ViewModel.

I tried to declare an instance:: ''' (activity as MainActivity) ''' inside my ViewModel class, but this throws up an error.

I guess the way I have declared LiveData variables is not really the best. All I wanted was to access static data of temperature variables (a list of 6. But MutableLiveData<List<Int>> wasn't really working out.

Please also suggest how else can I make my ViewModel and WebSocket talk to each other.

Thanks in advance.


Solution

  • problem :

    you have two big mistakes

    1-declare web web Socket in activity or fragment

    2-use activity in its view model

    explain concept:

    1-you have to declare separated class to web socket implement (create instance ,listen ,invoke,connect and disconnect) to apply single responsibility principle

    2-In MVVM the relation between view and view model is one direction view observe observable inside view model and but view model has no reference to view unlike MVP relation be 2 direction so you shouldn't declare your main activity in side view model

    Solution:

    1-socket class

    class SocketService{
        companion object {val instance :SocketService}
        fun connect() 
        fun disconnect()
        fun sendMessage(invokeMethodName:String,data:JsonObject)
        fun subscribe(listenMethodName:String,listner:Listner)
        }
    

    2-view model

      val receiveMessageResponse = MutableLiveData<String>()
          SocketService.instance!!.subscribe(RECEIVE_MESSAGE, HubEventListener {
                    receiveMessageResponse.postValue(it)
                })
    

    3-activity

    viewModel.receiveMessageResponse.observe(this, Observer {
             //use the received message here
            })
    

    Conclustion:

    socketService ------> view model ----------> activity

    activity <-------- viewmodel <------------- socketService