我对异步方法有疑问。每次在其调用时都应重新启动。如何实现呢?
在我的Android应用程序中,我想按月分组在仪表板上显示电影。电影存储在领域数据库中,并且某些用户在本地拥有很多电影,因此该过程完成可能会花费很多时间。这就是为什么我想在新组准备就绪时每次刷新UI。问题是当领域数据库更改时(例如,当新电影从另一个服务到达时),我必须再次开始刷新过程。在新的刷新过程之前,必须停止上一个刷新,并且必须清除UI。
UI:
public class DashboardFragment extends BaseFragment {
//...
private DashboardViewModel viewModel;
private Observer<RealmResults<Movie>> movieObserver = movies -> {
if (movies != null && movies.isLoaded())
viewModel.refresh();
};
//...
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//...
viewModel.movies.observe(this, movieObserver);
//...
}
//...
}
ViewModel:
public class DashboardViewModel extends AndroidViewModel {
//..
public RealmLiveDataResult<Movie> movies;
//...
public DashboardViewModel(@NonNull Application application) {
super(application);
//This provides a RealmLiveDataResult to have an observable to catch all the changes
movies = new MoviesRepository().getMovies();
}
//...
void refresh() {
try (Realm realmDefault = Realm.getDefaultInstance()) {
realmDefault.executeTransactionAsync(realmAsync -> {
//If there are already rendered movies they should be cleared from the UI
clearUI();
//Find months contains movies
RealmResults<Movie> moviesByMonth = realmDefault
.where(Movie.class)
.distinct("dateMonth")
.sort("date", Sort.DESCENDING);
.findAll();
//Find movies by month
for (Movie movieByMonth : moviesByMonth) {
//When this loop is still running but the refresh is called again it causes problems on the UI:
//It shows groups from the both processes
RealmQuery<Movie> allMoviesByMonthQuery = realmAsync
.where(Movie.class)
.equalTo("dateMonth", movieByMonth.getDateMonth())
.sort("date", Sort.DESCENDING);
List<Movie> moviesInTheMonth = realmAsync.copyFromRealm(allMoviesByMonthQuery.findAll());
//The new group is ready
showNewGroupOnUI(movieByMonth.getDate(), moviesInTheMonth);
}
});
}
}
}
答案 0 :(得分:0)
在异步任务中,您可以覆盖onPreExcute()和onPostExecute()。首先,创建类似于isCurrentlyLoading的布尔值并将其初始化为false。然后在调用加载之前检查这是isCurrentlyLoading是否为假
@Override
protected void onPreExecute() {
isCurrentlyLoading = true;
}
@Override
protected void onPostExecute(String result) {
isCurrentlyLoading = false;
}