简体   繁体   English

在 onPause() 期间使用协程保存数据(避免 ViewModel 取消和全局协程范围)

[英]Saving data with coroutines during onPause() (avoiding ViewModel cancellation and global coroutine scope)

Upon saving some data(to room) during onPause() with在 onPause() 期间保存一些数据(到房间)时

this.viewModelScope.launch(Dispatchers.IO){ repo.updateNote(id, text) } this.viewModelScope.launch(Dispatchers.IO){ repo.updateNote(id, text) }

I noticed that save does not happen most of the time, because viewModelScope is cancelled if user is navigating away from the fragment.我注意到大多数情况下都不会保存,因为如果用户离开片段,viewModelScope 会被取消。

Since using some type of global scope seems to be frowned upon for various reasons, is there an elegant way to Fire-And-Forget this db-save without tying it to ViewModelScope?由于使用某种类型的全局 scope 似乎因各种原因不受欢迎,是否有一种优雅的方法可以在不将其绑定到 ViewModelScope 的情况下对这个 db-save 进行“一劳永逸”?

I could create a service for this but it feels like an ugly hack, I could also use runBlocking which works, but can potentially hang the fragment, I'm looking for an elegant way to do this with coroutines.我可以为此创建一个服务,但感觉就像一个丑陋的黑客,我也可以使用 runBlocking ,它可以工作,但可能会挂起片段,我正在寻找一种优雅的方式来使用协程来做到这一点。

Fire and forget is exactly what GlobalScope is for: things that shouldn't be cancelled, so just use that.即发即弃正是GlobalScope的用途:不应该取消的事情,所以就使用它。

GlobalScope.launch(Dispatchers.IO){ repo.updateNote(id, text) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM