Skip to content

Instantly share code, notes, and snippets.

@haifengkao
Last active September 1, 2020 12:01
Show Gist options
  • Save haifengkao/da9ff614518976f374186028d8361ee6 to your computer and use it in GitHub Desktop.
Save haifengkao/da9ff614518976f374186028d8361ee6 to your computer and use it in GitHub Desktop.
combineLatest test
import Cocoa
import Combine
var subscriptions = Set<AnyCancellable>()
func futureIncrement(
integer: Int,
afterDelay delay: TimeInterval) -> AnyPublisher<Int, Never> {
Deferred {
Future<Int, Never> { promise in
print("init")
promise(.success(integer + 1))
}
}.subscribe(on: DispatchQueue.main).eraseToAnyPublisher()
}
let future = futureIncrement(integer: 1, afterDelay: 3)
future
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)
future
.sink(receiveCompletion: { print("Second", $0) },
receiveValue: { print("Second", $0) })
.store(in: &subscriptions)
Just(2).combineLatest(future).sink(receiveCompletion: { print("you won't see me", $0) },
receiveValue: { print("never 1", $0) })
.store(in: &subscriptions)
future.combineLatest(Just(2)).sink(receiveCompletion: { print("you won't see me, too", $0) },
receiveValue: { print("never 2", $0) })
.store(in: &subscriptions)
@ytyubox
Copy link

ytyubox commented Aug 31, 2020

/* line 19 */  let future = futureIncrement(integer: 1, afterDelay: 3).share()

Future 是少數幾個 class 的 Publisher,很容易誤會。

@dsxsxsxs
Copy link

dsxsxsxs commented Sep 1, 2020

delay沒被用到欸,冗余參數?
對combine不熟,不過這看起來跟subscribe(on:)沒關係呀🤔
share就好了,況乎為何要subscribe(on: ?

為何subscribe(on:)會有影響我也不懂哈

@dsxsxsxs
Copy link

dsxsxsxs commented Sep 1, 2020

Just(2)
    .subscribe(on: DispatchQueue.global())
    .combineLatest(Just(1))
    .sink(
        receiveCompletion: { print("you won't see me", $0) },
        receiveValue: { print("never", $0)
    })
    .store(in: &subscriptions)

這樣寫也不會動,我覺得這是bug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment