LoginSignup
0
1

More than 1 year has passed since last update.

【SwiftUI】Combineで初回だけ値を流さない

Posted at

はじめに

Combineを使用して値の監視を行うコードを書いていたのですが、躓いたポイントがあったので記録しておきます。
改善前のコードではViewModelが初期化されたタイミングでも値が流れてきてしまいます。
初期化の段階では値は変化していないので値は流したくありません。
初回のみ値を流さないようにすることでこの問題を解決しました。

改善前の実装

ViewModel
import Combine

final class ViewModel: ObservableObject {
    @Published var text: String = ""

    private var cancellable = Set<AnyCancellable>()

    init() {
        $text
            .sink { _ in
                print("値が変化しました")
            }
            .store(in: &cancellable)
    }
}

改善後の実装

ViewModel
import Combine

final class ViewModel: ObservableObject {
    @Published var text: String = ""

    private var cancellable = Set<AnyCancellable>()

    init() {
        $text
+           .dropFirst()
            .sink { _ in
                print("値が変化しました")
            }
            .store(in: &cancellable)
    }
}

おわり

Combineは開発が終わったってTwitterで話題なのでちょっと悲しいです

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