1

I am having this problem even though I used async in Realm. The lag is very noticeable. Is there something wrong with how I code it? This is my code:

    RealmConfiguration configuration = new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .build();

    realm = Realm.getInstance(configuration);

    itemCategoryName = getIntent().getExtras().getString("category", "");
    itemCategoryName = itemCategoryName.toLowerCase();

    shopItemList = new ArrayList<>();

    shopItemAdapter = new ShopItemAdapter(this, shopItemList);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    recyclerView.setAdapter(shopItemAdapter);


    realm.where(ShopItem.class).contains("category", itemCategoryName, Case.INSENSITIVE).findAllAsync()
    .addChangeListener(new RealmChangeListener<RealmResults<ShopItem>>() {
        @Override
        public void onChange(RealmResults<ShopItem> shopItems) {
            shopItemList.addAll(shopItems);

            shopItemAdapter.notifyDataSetChanged();
        }
    });

2 Answers2

1

Your code seems fine, keep in mind that network, database operations and many more should not be run on the UI thread. Use asynctasks, other threads, etc. for this tasks, so your application won't lag loading or performing this tasks.

Check this post for more information.

javdromero
  • 1,850
  • 2
  • 11
  • 19
  • Hmm, so basically the findAllAsync() from realm is not really asnyc? I thought that the onChange() method receives the value from the findAllAsync() after it has finished getting the results. – Junn Dobit Paras Apr 05 '21 at 07:44
0

It seems that onChange() is on the UI thread since when I commented the notifyDataSetChanged(), the adapter shows the list. I just made a new runnable inside the onChange() then it fixed that lag problem.

        @Override
        public void onChange(final RealmResults<ShopItem> shopItems) {
            Handler handler = new Handler();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    shopItemList.addAll(shopItems);
                    shopItemAdapter.notifyDataSetChanged();
                }
            });
        }