如何避免在我的 Android Room 存储库中出现许多 AsyncTask 类? [英] How to avoid occurring many AsyncTask class in my Android Room repository?

查看:22
本文介绍了如何避免在我的 Android Room 存储库中出现许多 AsyncTask 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 google-developer-training,我在其中找到了 repository class 的示例.我尝试简化我的 SportRepository 类.我想知道如何避免在我的代码中重复 inner class ...AsyncTask .这是非常示例的示例:

@Singleton类运动库{val LOG_TAG = SportRepository::class.java.name@注入Lateinit var sportDAO:SportDAO变量列表:LiveData>在里面 {App.app().appComponent()?.inject(this)列表 = SportDAO.getAll()}有趣的插入(运动:运动){insertAsyncTask().execute(sport)}有趣的更新(运动:运动){updateAsyncTask().execute(sport)}有趣的删除(运动:运动){deleteAsyncTask().execute(sport)}@SuppressLint("StaticFieldLeak")私有内部类 insertAsyncTask() : AsyncTask() {覆盖乐趣 doInBackground(vararg p0: Sport): Void?{SportDAO.insert(p0.get(0))返回空}}@SuppressLint("StaticFieldLeak")私有内部类 updateAsyncTask() : AsyncTask() {覆盖乐趣 doInBackground(vararg p0: Sport): Void?{SportDAO.update(p0[0])返回空}}@SuppressLint("StaticFieldLeak")私有内部类 deleteAsyncTask() : AsyncTask() {覆盖乐趣 doInBackground(vararg p0: Sport): Void?{SportDAO.delete(p0[0])返回空}}}

AsyncTask 类仅在名称和从 SportDAO 类调用的方法类型上有所不同.

有没有办法避免创建许多几乎相同的AsyncTask 类?

我还没有找到任何如何简化它的例子.

解决方案

好吧,我遇到了同样的情况.我使用了 3 种解决方案.1. 使用接收.返回一个 Flowable,并在不同的线程上观察它.2. 使用 LiveData.3. 异步任务.这就是我通过使用泛型来避免多个异步任务的方式.我希望这就是你要找的.

这是将执行查询的类.

/**** @param <T>预期结果类型*/公共抽象类 DaoAsyncProcessor<T>{公共接口 DaoProcessCallback{void onResult(T 结果);}私有 DaoProcessCallback daoProcessCallback;公共 DaoAsyncProcessor(DaoProcessCallback daoProcessCallback) {this.daoProcessCallback = daoProcessCallback;}受保护的抽象 T doAsync();公共无效开始(){new DaoProcessAsyncTask().execute();}私有类 DaoProcessAsyncTask 扩展了 AsyncTask{@覆盖受保护的 T doInBackground(Void... params) {返回 doAsync();}@覆盖受保护的无效 onPostExecute(T t) {if(daoProcessCallback != null)daoProcessCallback.onResult(t);}}}

现在查询

fun putAllUsersAsync(vararg users: User) {对象:DaoAsyncProcessor(空){覆盖乐趣 doAsync(): Unit {yourDao.insertAll(*users)}}.开始()}

另一个获取数据的例子.

fun getAllUsers(callback: DaoAsyncProcessor.DaoProcessCallback>) {对象:DaoAsyncProcessor>(回调){覆盖 fun doAsync(): List{返回 yourDao.getAll()}}.开始()

您可以调用 getAllUsers 并传递回调以获取数据.

根据要求,这是 Kotlin 的等价物

抽象类 DaoAsyncProcessor(val daoProcessCallback: DaoProcessCallback?) {接口 DaoProcessCallback{有趣的结果(结果:T)}受保护的抽象乐趣 doAsync(): T有趣的开始(){DaoProcessAsyncTask().execute()}私有内部类 DaoProcessAsyncTask : AsyncTask() {覆盖 fun doInBackground(vararg params: Void): T {返回 doAsync()}覆盖乐趣 onPostExecute(t: T) {daoProcessCallback?.onResult(t)}}}

I'm learning how to use Android Room from google-developer-training, where I found example of repository class. I try to simplify my SportRepository class. I wonder how to avoid repetition of inner class ...AsyncTask in my code. Here is very sample example:

@Singleton
class SportRepository {
    val LOG_TAG = SportRepository::class.java.name

    @Inject
    lateinit var sportDAO: SportDAO
    var list: LiveData<List<Sport>>

    init {
        App.app().appComponent()?.inject(this)
        list = sportDAO.getAll()
    }

    fun insert(sport: Sport) {
        insertAsyncTask().execute(sport)
    }

    fun update(sport: Sport){
        updateAsyncTask().execute(sport)
    }

    fun delete(sport: Sport) {
        deleteAsyncTask().execute(sport)
    }

    @SuppressLint("StaticFieldLeak")
    private inner class insertAsyncTask() : AsyncTask<Sport, Void, Void>() {
        override fun doInBackground(vararg p0: Sport): Void? {
            sportDAO.insert(p0.get(0))
            return null
        }
    }

    @SuppressLint("StaticFieldLeak")
    private inner class updateAsyncTask() : AsyncTask<Sport, Void, Void>() {
        override fun doInBackground(vararg p0: Sport): Void? {
            sportDAO.update(p0[0])
            return null
        }
    }

    @SuppressLint("StaticFieldLeak")
    private inner class deleteAsyncTask() : AsyncTask<Sport, Void, Void>() {
        override fun doInBackground(vararg p0: Sport): Void? {
            sportDAO.delete(p0[0])
            return null
        }
    }
}

The AsyncTask classes differ only in name and in kind of method invoke from sportDAO class.

Is there any way to avoid creating many almost the same AsyncTask classes?

I've not found any example how to simplify that.

解决方案

Ok, I faced the same. There are 3 solutions that I use. 1. Use RX. Return a Flowable, and observe it on different thread. 2. Use LiveData. 3. Async Task. This is how I avoid multiple async tasks by using Generics. I hope this is what you are looking for.

This is the class that will perform your queries.

/**
 *
 * @param <T> type of result expected
 */
public abstract class DaoAsyncProcessor<T> {

    public interface DaoProcessCallback<T>{
        void  onResult(T result);
    }

    private DaoProcessCallback daoProcessCallback;

    public DaoAsyncProcessor(DaoProcessCallback daoProcessCallback) {
        this.daoProcessCallback = daoProcessCallback;
    }

    protected abstract T doAsync();

    public void start(){
        new DaoProcessAsyncTask().execute();
    }

    private class DaoProcessAsyncTask extends AsyncTask<Void, Void, T>{

        @Override
        protected T doInBackground(Void... params) {
            return doAsync();
        }

        @Override
        protected void onPostExecute(T t) {
            if(daoProcessCallback != null)
                daoProcessCallback.onResult(t);
        }
    }
}

Now for querying

fun putAllUsersAsync(vararg users: User) {
            object : DaoAsyncProcessor<Unit>(null) {
                override fun doAsync(): Unit {
                    yourDao.insertAll(*users)
                }

            }.start()
        }

Another example of fetching data.

fun getAllUsers(callback: DaoAsyncProcessor.DaoProcessCallback<List<User>>) {
            object : DaoAsyncProcessor<List<User>>(callback) {
                override fun doAsync(): List<User> {
                    return yourDao.getAll()
                }

            }.start()

You can call getAllUsers and pass a callback for getting the data.

As requested, this is the Kotlin equivalent

abstract class DaoAsyncProcessor<T>(val daoProcessCallback: DaoProcessCallback<T>?) {

    interface DaoProcessCallback<T> {
        fun onResult(result: T)
    }


    protected abstract fun doAsync(): T

    fun start() {
        DaoProcessAsyncTask().execute()
    }

    private inner class DaoProcessAsyncTask : AsyncTask<Void, Void, T>() {

        override fun doInBackground(vararg params: Void): T {
            return doAsync()
        }

        override fun onPostExecute(t: T) {
            daoProcessCallback?.onResult(t)
        }
    }
}

这篇关于如何避免在我的 Android Room 存储库中出现许多 AsyncTask 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆