在我的应用程序中,有一个带有进度条的日化屏幕。这个序列化的一个步骤应该显示一个对话框。只有当用户与此alertdialog交互时,序列化过程才会继续。此对话框警报应可重复使用,因为它可以以相同的逻辑显示在其他屏幕中。我必须将它从java线程移植到kotlin协程。我刚刚开始使用flow和coroutines,我正在尝试这样做:
@HiltViewModel
class MainViewModel @Inject constructor(
val dataRepository: DataRepository,
val analyticsHelper: AnalyticsHelper,
val blockingPopupViewModelDelegate: BlockingPopupViewModelDelegate
) : ViewModel() {
val progressStatus: LiveData<ProgressStatus>
get() = _progressStatus
private val _progressStatus = MutableLiveData<ProgressStatus>()
// SIDE EFFECTS: Navigation actions
private val _navigationActions = Channel<MainNavigationAction>(capacity = Channel.CONFLATED)
// Exposed with receiveAsFlow to make sure that only one observer receives updates.
val navigationActions = _navigationActions.receiveAsFlow()
val appVersionCheck:Boolean = true
fun pressStartButton(){
analyticsHelper.log("pressStartButton()")
viewModelScope.launch(Dispatchers.Main) {
supervisorScope {
_progressStatus.value = ProgressStatus()
if(appVersionCheck) {
//check version and go on
analyticsHelper.log("check version and go on")
_navigationActions.tryOffer(MainNavigationAction.OpenAppVersionDialogAction)
analyticsHelper.log("end try offer")
withContext(Dispatchers.IO){
blockingPopupViewModelDelegate.okVersion.collect {
analyticsHelper.log("okVersion check")
if(it){
downloadProcess()
}
}
}
} else {
downloadProcess()
}
}
}
analyticsHelper.log("end pressStartButton")
}
@HiltViewModel
class BlockingPopupDialogViewModel @Inject constructor(appVersionDialogFragment: BlockingPopupViewModelDelegate) : ViewModel(), BlockingPopupViewModelDelegate by appVersionDialogFragment {
private val _viewType = Channel<BlockingPopupDialogView>(capacity = Channel.CONFLATED)
// Exposed with receiveAsFlow to make sure that only one observer receives updates.
val viewType = _viewType.receiveAsFlow()
init {
_viewType.trySend(BlockingPopupDialogView.Downloading)
}
}
interface BlockingPopupViewModelDelegate {
val okVersion: Flow<Boolean>
fun pressOk()
}
@Singleton
class MyBlockingPopupViewModelDelegate @Inject constructor() : BlockingPopupViewModelDelegate{
// SIDE EFFECTS: Error messages
// Guard against too many error messages by limiting to 3, keeping the oldest.
private val _okVersion = Channel<Boolean>(1, BufferOverflow.DROP_LATEST)
override val okVersion: Flow<Boolean> = _okVersion.receiveAsFlow()
override fun pressOk(){
_okVersion.trySend(true)
}
}
但这并不好,是一团糟。我也有一份git回购协议,但我不记得是否可以发布。
暂无答案!
目前还没有任何答案,快来回答吧!