0
1

More than 3 years have passed since last update.

Combine.Futureのイニシャライザに渡すクロージャを非同期に実行するExtension

Posted at

なにこれ?

FutureってFutureパターンのFutureじゃないの?
なんで生成時既に値が確定してるの?
それってJustじゃね?

クロージャ内でDispatchQueueを使って非同期にしてみたけど、面倒くさい。
ということで作ってみました。

import Combine

extension Future {

    convenience init<S: Scheduler>(on scheduler: S, _ attemptToFulfill: @escaping (@escaping Promise) -> Void) {

        self.init { promise in
            scheduler.schedule {
                attemptToFulfill(promise)
            }
        }
    }
}

使い方


let future = Future<Int, Error> { promise in
                 DispatchQueue.global().async {
                     sleep(1)
                     promise(.success(1))
                 }
}

これが

let future = Future<Int, Error>(on: DispatchQueue.global()) { promise in
                 sleep(1)
                 promise(.success(1))
}

こうなります。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1