Я использую SingleLiveEvent для передачи моей модели ViewModel и моей активности. Примерно так (псевдокод):
class MyActivity: BaseActivity{
fun onCreate(){
//Init viewmodel and so on
viewModel.commands.observe(this, { command ->
logger.debug("Command received","------>>>>>>>"+command.javaClass.simpleName)
processCommand(command)
})
}
}
И моя ViewModel выглядит примерно так:
class MyViewModel(application: Application) : BaseAndroidViewModel(application) {
val command: SingleLiveEvent<CustomCommands> = SingleLiveEvent()
init{
loadOneThing()
command.postValue(CustomCommands.MessageCommand("one thing loaded"))
loadAnotherThing()
command.postValue(CustomCommands.MessageCommand("another thing loaded"))
}
}
Проблема, с которой я столкнулся, заключается в том, что Activity получает только последнюю команду, и это для каждого дизайна. SingleLiveEvent - это дочерний класс из LiveData, и в документации для метода postValue говорится следующее:
* If you called this method multiple times before a main thread executed a posted task, only * the last value would be dispatched.
Interestingly, if I set a breakpoint on the line that posts the commands, the emulator/device/main thread has time enough to process the first command, and the second command is sent too. But when executing the app without breakpoints, if the tasks that the viewmodel does between commands are done very fast (no rest requests or things like that, but some calculations), the main thread does not have time enough to finish the first command, and the second command is ignored.
Но мне действительно нужно View для получения всех событий / команд, которые отправляет ViewModel.
Я полагаю, что ни SingleLiveEvent, ни LiveData не подходят для этого варианта использования из-за проблемы повторной отправки уже использованных событий при повороте устройства и т. Д.
Кто-нибудь знает, как это сделать лучше?
Заранее спасибо!