[英]How to run ProgressDialog with AsyncTask in ViewModel
I recently started to use MVVM
pattern with LiveData
and Room in my Android app. 我最近开始在我的Android应用程序
LiveData
MVVM
模式与LiveData
和Room一起使用。
In my ViewModel
I fetch data from db using AsyncTask
. 在我的
ViewModel
我使用AsyncTask
从db获取数据。 But sometimes I load from db some more heavy stuff(like list with few thousands items). 但是有时我会从数据库加载一些更重的东西(例如包含数千个项目的列表)。 Normally I would add a ProgressDialog to AsyncTask, start it in onPreExecute method and close it in onPostExecute.
通常,我会向AsyncTask添加一个ProgressDialog,在onPreExecute方法中启动它,然后在onPostExecute中关闭它。 But ProgressDialog needs a
Context
: 但是ProgressDialog需要一个
Context
:
new ProgressDialog(Context ctx)
I've read about separation between View ( Activity
) and ViewModel
and that I should not use activities context in ViewModel
classes. 我已经读过关于View(
Activity
)和ViewModel
之间的分离的知识,并且我不应该在ViewModel
类中使用活动上下文。 So how can I achieve that without having the activity context in my ViewModel
? 那么,如何在
ViewModel
中没有活动上下文的情况下实现呢?
Maybe I should use a different approach? 也许我应该使用其他方法?
You can write the show/hide progress dialog inside Activity
. 您可以在
Activity
内编写显示/隐藏进度对话框。
Then ViewModel
can notify to Activity
to show dialog (using listener
) 然后,
ViewModel
可以通知Activity
以显示对话框(使用listener
)
You can also check https://github.com/googlesamples/android-architecture/tree/dev-todo-mvvm-live for more details 您还可以查看https://github.com/googlesamples/android-architecture/tree/dev-todo-mvvm-live了解更多详细信息
And example using a listener to notify and pass data 以及使用侦听器通知和传递数据的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.