初期化のために一度だけ実行する処理はlazy var
で行う。
#3
YusukeHosonuma
started this conversation in
Pending
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Overview
ViewModel などに
@MainActor
を適用し、かつ Initializer をnonisolated
でマークしている場合、task
(onAppear
)での初期化が必要になる場合がある(Publisher
の接続など)。その際に
lazy var
を利用すれば、一度だけしか実行されないことを保証できる。Discussion
lazy var
はマルチスレッド下において、複数回実行される可能性があるが、このコード例の場合@MainActor
によって保護されているので問題ない。なお、
lazy var
ブロック内でasync
なメソッドを呼び出すことはできない。その際は、以下のようなdefer
とguard
を使ったコードパターンを活用すると良い。Why not?
async
なメソッドを呼ぶか呼ばないかによって、コードの書き方が変わるというのもややこしいので、前述したようなシンプルなコードに統一した方がベターな可能性も高い。(まだ頻度が読めていない)Beta Was this translation helpful? Give feedback.
All reactions