Skip to content

Instantly share code, notes, and snippets.

@lisamariewatkins
Created January 23, 2021 03:03
Show Gist options
  • Save lisamariewatkins/1d13d758c2d0ccff4ae89654855120e6 to your computer and use it in GitHub Desktop.
Save lisamariewatkins/1d13d758c2d0ccff4ae89654855120e6 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.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
init {
loadTextFromNetwork()
}
private 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