Challenge: Live Data

I can’t figure out how to complete the first Challenge of Ch. 22 “Live Data”.
Could someone give me a hint?

Thanks.

Same issue here. cant complete.

Regards,
Shane.
Letgo Kissanime

Since the API call is asynchronous, there has to be a delay before the character info is shown. I made a “placeholder” character that has as the name “Generating character…” to tell the user something is happening.

// in CharacterGenerator.kt
fun placeHolderCharacter() = CharacterData("Generating Character...", "", "", "", "")

Now inside onCreate() when checking the savedInstanceState, if it returns null then fetch the API and show the placeholder

characterData = savedInstanceState?.characterData ?: let {
        fetchCharacterFromAPI()
        CharacterGenerator.placeHolderCharacter()
    }

Where fetchCharacterFromAPI() is the contents of the click listener from Listing 22.8.

This only performs the initial fetch when the bundle is null, so after doing the initial retrieval and the user rotates the device, the character is stored.

Slightly different solution where I don’t have any placeholders:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_new_character)

savedInstanceState?.let {
    characterData = it.characterData
} ?: updateCharacterFromWeb()

generateButton.setOnClickListener {
    updateCharacterFromWeb()
}
}

private fun updateCharacterFromWeb() {
GlobalScope.launch(Dispatchers.Main) {
    characterData = fetchCharacterDataAsync().await()
    displayCharacterData()
}
}