MvvmCross - Calling Web Service from View Model

后端 未结 1 1577
一生所求
一生所求 2021-01-01 05:00

I\'m new to MvvmCross and Android development. I have a need to call to POST data to a JSON web service in my view model. I then need to display the result of the web servic

相关标签:
1条回答
  • 2021-01-01 05:31

    In general, I put this kind of WebService call in the Model rather than in the ViewModel - it makes both the ViewModel and the WebService client code much more reusable.

    Some simple examples of this are in:

    • the twittersearch sample - https://github.com/slodge/MvvmCross/tree/v3/Sample%20-%20TwitterSearch
    • the Dilbert sample - https://github.com/slodge/MvvmCross-Tutorials/tree/master/DailyDilbert

    I know from my Windows Phone dev experience, I would need to check to see if I'm on the UI thread, if not, I'd have to do some Deployment.stuff. But, with the MvvmCross approach, I'm not sure a) if I have to do that and

    Yes, all communication from ViewModel->View should be on the UI thread.

    b) if that is even an option since the view model should work with both Android and iOS.

    MvvmCross provides an interface to allow you to marshal execution onto the UI thread. In a ViewModel, this is easily done by calling InvokeOnMainThread(() => { /* your code */ })

    Behind the scenes, MvvmCross will also marshall all RaisePropertyChanged executions to the UI thread too. Note - that ObservableCollection updates are not automatically marshalled though - this is because ObservableCollection is a class that exists outside of MvvmCross.

    Regardless, there has to be a way to a) call a web service from a view model and

    See the samples (above)

    b) send a message back to the view so that the UI can be updated.

    In general you should not send these type of messages via events.

    Instead, you should:

    • update ViewModel properties
    • (occasionally) send Messages via a Messenger
    0 讨论(0)
提交回复
热议问题