Created
January 23, 2021 03:03
-
-
Save lisamariewatkins/1d13d758c2d0ccff4ae89654855120e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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