I have an observable that manages an object called Profile:
class Profile {
let name. : String
let surname : String
let avatar: String?
}
Observable<Profile>
This observable is binded to view model, who has a at the same time an observable property called
var initialMarks:Observable<String>
That are the initial letters of name and surname properties. This initial letters are shown in case avatar property is nil.
I have a function that returns initial letters in a string:
func initialLetters(first:String, second: String) -> String
How can I achieve this by using RxSwift any operators, to:
Many thanks.
This is just a simple mapping...
Here it is as it's own view model.
func initialMarks(for profile: Observable<Profile>) -> Observable<String> {
return profile
.compactMap { profile in
if profile.avatar == nil {
return initialLetters(first: profile.name, second: profile.surname)
}
else {
return nil
}
}
}
If you want to embed it in a view model struct/class you could do something like:
struct ViewModel {
let profile: Observable<Profile>
var initialMarks: Observable<String> {
return profile
.map { profile in
if profile.avatar == nil {
return initialLetters(first: profile.name, second: profile.surname)
}
else {
return ""
}
}
}
}
Also the two implementations above are subtly different depending on what you want... In the first one, it only emits initials when the avatar is nil, the second one emits an empty string when the avatar exists or initials when the avatar in nil.