LocationService
- locationSubject : 위치정보를 구독할 서브젝트
- locationManager : 위치 관리를 얘가 다한다
- didUpdateLocation : 위치 정보가 들어있음
- requestWhenInUseAuthorization : 위치 권한 허용 요청
- didChangeAuthorization : 위치 권한 허용 여부 확인
- requestLocation : 위치 권한 허용 함수
compactMap
: nil 값을 버리고 값이 있을 때만 전달
deffered
: 옵저버블을 미리 만들지 않고, 구독을 시작되면 옵저버블을 만든다
class LocationService {
static let shared = LocationService()
let disposeBag = DisposeBag()
let locationSubject = BehaviorSubject<CLLocationCoordinate2D?>(value: nil)
let locationManager = {
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
return locationManager
}()
private init() {
self.locationManager.rx.didUpdateLocations
.compactMap {$0.locations.last?.coordinate}
.bind(to: locationSubject)
.disposed(by: disposeBag)
self.locationManager.startUpdatingLocation()
}
func requestLocation() -> Observable<CLAuthorizationStatus> {
return Observable<CLAuthorizationStatus>
.deferred { [weak self] in
guard let ss = self else { return .empty() }
ss.locationManager.requestWhenInUseAuthorization()
return ss.locationManager.rx.didChangeAuthorization
.map { $1 }
.filter { $0 != .notDetermined }
.do(onNext: { _ in ss.locationManager.startUpdatingLocation() })
.take(1)
}
}
}