Skip to content

Instantly share code, notes, and snippets.

@lisamariewatkins
Last active January 23, 2021 03:00
Show Gist options
  • Save lisamariewatkins/44a3faf2f10eeaf043193aa240b0f21e to your computer and use it in GitHub Desktop.
Save lisamariewatkins/44a3faf2f10eeaf043193aa240b0f21e to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val model: MainViewModel by viewModels()
model.loadTextFromNetwork()
model.displayText.observe(this, Observer { text ->
text_view.text = text
})
}
}
class MainViewModel(
private val repo: Repository
) : ViewModel() {
private val _displayText = MutableLiveData<String>()
val displayText: LiveData<String>
get() = _displayText
internal fun loadTextFromNetwork() = loadTextFromNetwork()
private fun loadTextFromNetwork() {
viewModelScope.launch {
try {
val response = repo.expensiveNetworkCall()
_displayText.postValue(response.text)
} catch (e: Exception) {
// error handling
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment