代码之家  ›  专栏  ›  技术社区  ›  Alin

在Kotlin的另一个线程中运行room insert的推荐方法

  •  2
  • Alin  · 技术社区  · 6 年前

    我在台阶上 Repository 我想实现跑步 @Insert 进入新线程,而不是在UI线程上。

    我发现有几种方法可以解决这个问题:

    1. 一些样品的使用 AsyncTask 并且在 doInBackground Dao 呼叫

    2. 谷歌向日葵样本使用 runOnIoThread 哪种方法可以 IO_EXECUTOR.execute(job) 哪里 IO_EXECUTOR = Executors.newSingleThreadExecutor

    3. 有些似乎有用 anko

    doAsync{ dao.insert(item) }

    推荐的方法是什么?

    1 回复  |  直到 6 年前
        1
  •  5
  •   EpicPandaForce    6 年前

    通常,您应该在一个接口下包装自己的执行器。

    public interface Scheduler {
        void runOnThread(Runnable runnable);
    }
    
    /**
     * A Scheduler implementation based on ModernAsyncTask with an unbounded task queue.
     **/
    public class IoScheduler implements Scheduler {
        private static final int CORE_POOL_SIZE = 5;
        private static final int MAXIMUM_POOL_SIZE = 128;
        private static final int KEEP_ALIVE = 1;
    
        private static final ThreadFactory sThreadFactory = new ThreadFactory() {
            private final AtomicInteger mCount = new AtomicInteger(1);
    
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "IoScheduler #" + mCount.getAndIncrement());
            }
        };
    
        private static final BlockingQueue<Runnable> sPoolWorkQueue =
                new LinkedBlockingQueue<Runnable>();
    
        /**
         * An {@link Executor} that can be used to execute tasks in parallel.
         */
        private static final Executor THREAD_POOL_EXECUTOR =
             new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
    
        @Override
        public void runOnThread(Runnable runnable) {
            THREAD_POOL_EXECUTOR.execute(runnable);
        }
    }
    

    你通常会用匕首:

    @Singleton
    public class IoScheduler implements Scheduler {
        @Inject
        IoScheduler() {}
        ...
    }
    
    @Module
    public class SchedulerModule {
        public static final String BACKGROUND = "BACKGROUND";
    
        @Named(BACKGROUND) // you can also use @Qualifier
        @Provides
        Scheduler ioScheduler(IoScheduler ioScheduler) {
            return ioScheduler;
        }
    }
    

    然后在其他地方使用

    @Singleton
    public class MyService {
        private final Scheduler ioScheduler;
    
        @Inject
        MyService(@Named(SchedulerModule.BACKGROUND) Scheduler ioScheduler) { // you can use @Qualifier here instead of @Named
            this.ioScheduler = ioScheduler;
        }
        ....
    }
    

    (尽管如此 ioScheduler 更适合读:对于写操作,您可能需要考虑一个单独的单线程执行器。)


    所以如果你读到它的结尾,它实际上是这样的方法:

    2.)谷歌向日葵样本使用 runOnIoThread 哪种方法可以 IO_EXECUTOR.execute(job) 哪里 IO_EXECUTOR = Executors.newSingleThreadExecutor