Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🍎 iOS Pull request
✅ 작업(과제) 내용
💡 새로 알게 된 내용
저는 각각의 상태를 가지고 있게 하기 위해 Subject들을
CurrentValueSubject로 movieSubject(영화 목록 저장하는 녀석), isLoadingSubject(로딩 상태 저장하는 녀석), errorSubject(에러 메세지 저장하는 녀석)을 만들어줬습니다. 처음 만들때 초기값도 넣었어요.transform에서 Input을 받아서 Output으로 반환해줍니다.viewWillAppear이벤트를 구독해두고 뷰컨에서viewWillAppear이벤트가 일어날 때 API 호출하는 클로저를 실행해 줬습니다.Subject를Publisher로 변환해서 반환시킵니다. 값이나 상태가 변할 때마다ViewController가 자동으로 변한 값을 받습니다.fetchMovies()에서는 처음에는isLoadingSubject.send(true), 즉isLoading구독자가true를 받도록 하다가 API 호출 후 성공이나 실패를 반환할 때 값을false로 바꿔줍니다.뷰컨에서는
Input용Subject인viewWillAppearSubject를 만들어줬습니다.viewWillAppear할 경우ViewModel의Input으로 전달되어fetchMovies가 실행됩니다.transform을 실행시켜Output을 받아요.output.movies는 메인 스레드에서 받고,movies값이 올 때마다 이 클로저 실행하여movies값을 갱신하고 이에 따라tableView의 데이터값도 갱신해요. 그리고 이 구독을 저장합니다.간단하게 흐름으로 나타내면 이렇습니다
왜 Subject에서 Publisher로, Publisher에서 Subject로? (헷갈리는 개념 정리)
캡슐화를 위해!
Output을 Subject 그대로 반환할 경우 ViewController가 직접 데이터 변경이 가능해지므로 위험합니다. 외부에서 값을 변경하지 못하도록 캡슐화해주기 위해서 Publisher로 반환해줍니다.
단방향 데이터 흐름을 보장하기 위해!
ViewModel → ViewController : 데이터 전달
ViewController → ViewModel : 이벤트 전달
Publisher로 주면 ViewController에서는 구독 후 읽기만 가능하니까 사용합니다.
직접 사용해보니 흐름이 더 명확해져서 따로 정리해보았습니다!
📸 스크린샷