I'm using ReactiveSwift + SDWebImage to download/cache userAvatars of an API and then I display them in my ViewControllers.
I have multiple ViewControllers which want to display the userAvatar, then they listen to its async loading.
What is the best way for me to implement the flow described below?
The flow I would like to create here is:
ViewControllerA
want to access userAvatar- it is the first time userAvatar is accessed then make an API request
ViewControllerA
listens for userAvatar signalsViewControllerA
temporarily display a placeholderViewControllerB
want to access userAvatarViewControllerB
listens for userAvatar signalsViewControllerB
temporarily display a placeholder- API request of the userAvatar is completed, then send a signal observed by the viewcontrollers
- viewcontrollers are refreshing their
UIImageView
with the fresh image
This is my actual code:
class ViewControllerA {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// ... Cell creation
// type(of: user) == User.self (see class User below)
user.loadAvatarImage()
disposable = user.image.producer
.observe(on: UIScheduler())
.startWithValues { image in
// image is is either a placeholder or the real avatar
cell.userImage.image = image
}
}
}
class ViewControllerB {
override func viewDidLoad() {
super.viewDidLoad()
// type(of: user) == User.self (see class User below)
user.loadAvatarImage()
disposable = user.image.producer
.observe(on: UIScheduler())
.startWithValues { image in
// image is is either a placeholder or the real avatar
headerImageView.image = image
}
}
}
class User: Mappable {
// ... User implementation
let avatarImage = MutableProperty<UIImage?>(nil)
// To call before accessing avatarImage.value
func loadAvatarImage() {
getAvatar { image in
self.avatarImageProperty.value = image
}
}
private func getAvatar(completion: @escaping ((UIImage) -> Void)) {
// ... Async image download
competion(image)
}
}
I don't find that calling user.loadAvatarImage()
before listening to the signal is very clean...
I know my code isn't so "Reactive", I still new with Reactive concept. Feel free to criticize, I'm trying to improve myself
Thanks in advance for your advice.