0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】Combineで同じ値を流さないようにする

Posted at

はじめに

Combineを使用していて、同じ値が流れてくると不便なことがありました。
同じ値を削除する機能を使ったので記録しておきます.

実装

以下は同じ値が何度も流れてきます。

import Foundation
import Combine

let subject = PassthroughSubject<Int, Never>()

var cancellable = Set<AnyCancellable>()

subject
    .sink { int in
        print(int)
    }
    .store(in: &cancellable)

subject.send(100)

subject.send(100)

subject.send(100)

subject.send(200)

subject.send(300)

subject.send(300)

subject.send(300)

subject.send(300)

subject.send(completion: .finished)

// success(100)
// success(100)
// success(100)
// success(200)
// success(300)
// success(300)
// success(300)
// success(300)

同じ値は除外します。

import Foundation
import Combine

let subject = PassthroughSubject<Result<Int, Error>, Never>()

var cancellable = Set<AnyCancellable>()

subject
    .removeDuplicates { beforeResult, afterResult in
        switch (beforeResult, afterResult) {
        case let (.success(beforeInt), .success(afterInt)):
            return beforeInt == afterInt
        default:
            return false
        }
    }
    .sink { int in
        print(int)
    }
    .store(in: &cancellable)

subject.send(.success(100))

subject.send(.success(100))

subject.send(.success(100))

subject.send(.success(200))

subject.send(.success(300))

subject.send(.success(300))

subject.send(.success(300))

subject.send(.success(300))

subject.send(completion: .finished)

// success(100)
// success(200)
// success(300)

おわり

単純な型であれば.removeDuplicate()だけです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?