Android支持库中的CompletableFuture?

时间:2016-07-06 10:21:16

标签: android java-8

所以我今天将Android Studio项目迁移到Java 8,Android API级别24和Jack工具链,以查看新功能,特别是lambdas和CompletableFuture

不幸的是,CompletableFuture似乎仅在API级别24上可用(我的该项目的最低API级别为16)。

您是否知道将CompletableFuture带入Android支持库的计划?它似乎是Promises模式的一个很好的解决方案。

4 个答案:

答案 0 :(得分:15)

streamsupport项目在其CompletableFuture组件中提供streamsupport-cfuture的后端,可用于Android开发,并支持所有设备。

使用

dependencies {
    compile 'net.sourceforge.streamsupport:streamsupport-cfuture:1.7.0'
}

或Android Studio 3.x的更现代的android-retrofuture分支

dependencies {
    compile 'net.sourceforge.streamsupport:android-retrofuture:1.7.0'
}

如果您可以使用Android Studio 3.x。

CompletableFuture JDK-8211010的新Java 12异常处理方法已在1.7.0版中集成

答案 1 :(得分:5)

Stefan Zobel提到的

import os from os import path import glob import numpy as np import cv2 import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Watcher: DIRECTORY_TO_WATCH = 'PATH' def __init__(self): self.observer = Observer() def run(self): event_handler = Handler() self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True) self.observer.start() try: while True: except: self.observer.stop() self.observer.join() class Handler(FileSystemEventHandler): @staticmethod def on_any_event(event): if event.is_directory: return None elif event.event_type == 'created': os.chdir("PATH") newest = max(glob.glob("PATH/*.mp4"), key=os.path.getctime) cap = cv2.VideoCapture(newest) cap.set(1,1420); def rescale_frame(frame, percent=25): width = int(frame.shape[1] * percent/ 100) height = int(frame.shape[0] * percent/ 100) dim = (width, height) return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA) while True: ret ,frame = cap.read() if type(frame) == type(None): break frame25 = rescale_frame(frame, percent=25) cv2.namedWindow('frame25',cv2.WINDOW_NORMAL) cv2.imshow('frame25',frame25) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == '__main__': w = Watcher() w.run() 库的答案特别针对Android Studio> = 3.0 desugar toolchain,请检查android-retrofuture

答案 2 :(得分:4)

相关且可能对您有用:Java: Optimizing an application using asynchronous programming

这个答案是关于Java 7上的CompletableFuture,使用上面评论中提到的库,而不是Android。但是,lib的文档声明它可以在Android上运行。我自己也没有用过它。

答案 3 :(得分:0)

如果您不需要CompletableFuture的所有功能(例如,结果链接),则可以使用此类(科特琳):

/**
 * A backport of Java `CompletableFuture` which works with old Androids.
 */
class CompletableFutureCompat<V> : Future<V> {
    private sealed class Result<out V> {
        abstract val value: V
        class Ok<V>(override val value: V) : Result<V>()
        class Error(val e: Throwable) : Result<Nothing>() {
            override val value: Nothing
                get() = throw e
        }
        object Cancel : Result<Nothing>() {
            override val value: Nothing
                get() = throw CancellationException()
        }
    }

    /**
     * Offers the completion result for [result].
     *
     * If this queue is not empty, the future is completed.
     */
    private val completion = LinkedBlockingQueue<Result<V>>(1)
    /**
     * Holds the result of the computation. Takes the item from [completion] upon running and provides it as a result.
     */
    private val result = FutureTask<V> { completion.peek()!!.value }
    /**
     * If not already completed, causes invocations of [get]
     * and related methods to throw the given exception.
     *
     * @param ex the exception
     * @return `true` if this invocation caused this CompletableFuture
     * to transition to a completed state, else `false`
     */
    fun completeExceptionally(ex: Throwable): Boolean {
        val offered = completion.offer(Result.Error(ex))
        if (offered) {
            result.run()
        }
        return offered
    }

    /**
     * If not already completed, completes this CompletableFuture with
     * a [CancellationException].
     *
     * @param mayInterruptIfRunning this value has no effect in this
     * implementation because interrupts are not used to control
     * processing.
     *
     * @return `true` if this task is now cancelled
     */
    override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
        val offered = completion.offer(Result.Cancel)
        if (offered) {
            result.cancel(mayInterruptIfRunning)
        }
        return offered
    }

    /**
     * If not already completed, sets the value returned by [get] and related methods to the given value.
     *
     * @param value the result value
     * @return `true` if this invocation caused this CompletableFuture
     * to transition to a completed state, else `false`
     */
    fun complete(value: V): Boolean {
        val offered = completion.offer(Result.Ok(value))
        if (offered) {
            result.run()
        }
        return offered
    }

    override fun isDone(): Boolean = completion.isNotEmpty()

    override fun get(): V = result.get()

    override fun get(timeout: Long, unit: TimeUnit): V = result.get(timeout, unit)

    override fun isCancelled(): Boolean = completion.peek() == Result.Cancel
}