Room存储库中出现许多AsyncTask类

Room存储库中出现许多AsyncTask类

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

问题描述

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

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
        }
    }
}

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

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

有什么方法可以避免创建许多几乎相同的AsyncTask类?

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

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

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

推荐答案

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

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.

这是将执行查询的类.

/**
 *
 * @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);
        }
    }
}

现在可以查询

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()

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

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

根据要求,这是Kotlin等效项

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类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:01