Android Livedata和JetPack组成:实时数据未更新时
固定在Livedata之后,观察者中的setContent并未被执行。所以我只是在空白的活动。这是怎么回事?它似乎在另一个具有类似模式的活动中起作用。
class TeamBuilderActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val imageIds = listOf(
R.mipmap.goblin_smiling_background,
R.mipmap.marker_goblin_axe_foreground,
R.mipmap.beholder_foreground,
R.mipmap.d20_background,
R.mipmap.marker_goblin_axe_foreground,
R.mipmap.goblin_smiling_foreground
)
val monsters = listOf(
GoblinoidFactory.Bugbear(), GoblinoidFactory.Goblin(), KoboldFactory.Kobold()
)
val viewModel = ViewModelProvider(this).get(TeamBuilderActivityViewModel::class.java)
val liveData = viewModel.getLiveData()
liveData.observe(this, Observer {
setContent {
Column {
Card {
Column(Modifier.padding(5.dp)) {
TeamBuilderComposables.ImageSlider(
imageIds = imageIds,
onClicked = viewModel::onClickImage
)
TeamBuilderComposables.RandomNameRoller(
inputStream = resources.openRawResource(R.raw.nicknames),
onClicked = viewModel::setName
)
TeamBuilderComposables.StatBlockChooser(
monsters = monsters,
onClicked = viewModel::onClickMonsterStatBlock
)
}
}
TeamBuilderComposables.CharacterInfo(
imageId = it.selectedImageId,
monster = it.selectedMonster,
name = it.selectedName
)
}
}
})
}
}
The setContent in the Observer is not being executed after being attached to the liveData. So I'm just getting a blank activity. What's going on here? It seems to work in another activity with a similar pattern.
class TeamBuilderActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val imageIds = listOf(
R.mipmap.goblin_smiling_background,
R.mipmap.marker_goblin_axe_foreground,
R.mipmap.beholder_foreground,
R.mipmap.d20_background,
R.mipmap.marker_goblin_axe_foreground,
R.mipmap.goblin_smiling_foreground
)
val monsters = listOf(
GoblinoidFactory.Bugbear(), GoblinoidFactory.Goblin(), KoboldFactory.Kobold()
)
val viewModel = ViewModelProvider(this).get(TeamBuilderActivityViewModel::class.java)
val liveData = viewModel.getLiveData()
liveData.observe(this, Observer {
setContent {
Column {
Card {
Column(Modifier.padding(5.dp)) {
TeamBuilderComposables.ImageSlider(
imageIds = imageIds,
onClicked = viewModel::onClickImage
)
TeamBuilderComposables.RandomNameRoller(
inputStream = resources.openRawResource(R.raw.nicknames),
onClicked = viewModel::setName
)
TeamBuilderComposables.StatBlockChooser(
monsters = monsters,
onClicked = viewModel::onClickMonsterStatBlock
)
}
}
TeamBuilderComposables.CharacterInfo(
imageId = it.selectedImageId,
monster = it.selectedMonster,
name = it.selectedName
)
}
}
})
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的……我发现处理此问题的最佳方法是将实时数据转换为组合块内部的状态对象:
OK … I found that the best way to handle this is to turn the live data into a state object inside the compose block with: