Last active
January 23, 2021 03:00
-
-
Save lisamariewatkins/44a3faf2f10eeaf043193aa240b0f21e 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.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