我有此方法返回用户可见
internal func getUser() -> Observable<User> {
let result = withRealm("getting user") { realm -> Observable<User> in
let realm = try Realm()
let user = realm.objects(User.self).first
return Observable.from(optional: user)
}
return result ?? .empty()
}
现在,我想拥有另一种方法,如果用户登录,该方法将返回我,该怎么做?
private var _isLoggedIn: Observable<User> {
return getUser().count > 0 //error
}
答案 0 :(得分:0)
我建议改用枚举以摆脱可选项,以便于管理:
enum LoginState {
case loggedIn(user: User)
case loggedOut
}
internal func getLoginState() -> Observable<LoginState> {
let user = withRealm("getting user") { realm -> User? in
let realm = try Realm()
return realm.objects(User.self).first
}
if let user = user {
return Observable.just(.loggedIn(user))
} else {
return Observable.just(.loggedOut)
}
}
private var _isLoggedIn: Observable<Bool> {
return getLoginState().map {
switch $0 {
case .loggedIn: return true
case .loggedOut: return false
}
}
}