在onactivityresult上查看模型后崩溃,在onSaveInstanceState上无法执行此操作



我正在尝试一个简单的流程,从我的活动开始,我打开文件选择器,然后到视图模型,这会导致以下崩溃:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

这是造成这次崩溃的代码:

private val mainViewModel: MainViewModel by viewModels()
private var activityResultLaunch = registerForActivityResult(StartActivityForResult()) { result ->
val fileUri = result.data?.data ?: return@registerForActivityResult
val stream = contentResolver.openInputStream(fileUri) ?: return@registerForActivityResult
uploadFiles(stream)
}
private fun uploadFiles(stream: InputStream) {
lifecycleScope.launchWhenStarted {
mainViewModel.uploadFiles(
stream = stream
).asLiveData().observe(this@MainActivity, {
handleFileUploadStatus(it)
})
}
}
@HiltViewModel
class MainViewModel @Inject constructor(
private val filesRepository: FilesRepository
) : ViewModel() {
suspend fun uploadFiles(stream: InputStream): Flow<UploadStatusUI> {
return filesRepository.uploadFiles(listOf(stream))
}
}

经过一番研究,我在谷歌的问题跟踪器上发现了这个问题,在firefox的github上发现了另一个问题,但没有任何效果。显然,这个问题在生命周期2.3.1中得到了解决,但我仍然面临着它

以下是我的版本:

"androidx.lifecycle:lifecycle视图模型ktx:2.4.0";

"androidx.lifecycle:lifecycle视图模型保存日期:2.4.0";

提前感谢!

编辑:崩溃堆栈跟踪此处

根据您链接到的问题,其他人仍然有同样的问题,所以该库中可能存在错误。也许可以试试变通一下。而不是在活动中做所有的工作:

private fun uploadFiles(stream: InputStream) {
lifecycleScope.launchWhenStarted {
mainViewModel.uploadFiles(
stream = stream
).asLiveData().observe(this@MainActivity, {
handleFileUploadStatus(it)
})
}
}

分解:

首先,虚拟机中的实时数据对象:

private val _uploadStatusLiveData = MutableLiveData<UploadStatusUI>()
val uploadStatusLiveData: LiveData<UploadStatusUI> get() = _uploadStatusUI

接下来更改VM挂起功能以启动协同程序:

// Not suspend, no return type - instead collect repo flow and pass to live data
fun uploadFiles(stream: InputStream) {
viewModelScope.launch(Dispatchers.IO) {
filesRepository.uploadFiles(listOf(stream)).collect {
_uploadStatusLiveData.postValue(it)
}
}   
}

最后,观察活动的变化:

fun onCreate(...) {
viewModel.uploadStatusLiveData.observe(this) {
handleUploadStatus(it)
}
}

并手动启动流程:

fun onStart(...) {
viewModel.uploadFiles(stream)
}

相关内容

  • 没有找到相关文章

最新更新