Classes and threading in iOS: viewModel scenario - ios

I´m following an MVVM architecture, so I have a viewController that holds a reference to its viewModel like this:
lazy private var viewModel: MyViewModel = {
return MyViewModel()
}()
Such viewModel is initialized within the viewDidLoad() method this way:
private func initViewModel() {
viewModel.onModelChange = { [unowned self] () in
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
viewModel.getData()
}
Where getData() viewModel's method calls another object to perform a networking async task to retrieve the data to be displayed by the viewController:
func getData() {
guard let url = ServiceAPI.getServiceUrl() else {
return
}
dataProvider.getData(url: url, completion: {[weak self] (result, error) -> Void in
if let error = error {
self?.model = [MyCustomModel]()
} else {
if let result = result {
self?.total = result.data.total
self?.processFetchedData(items: result.data.items)
} else {
self?.model = [MyCustomModel]()
}
}
})
}
Regarding threading, the scenario is: the viewModel is initialized by the viewController and bound to it in the main thread. The viewModel is asked to call a networking object (dataProvider), also initialized in the main thread. dataProvider calls also from the main thread an URLSessionDataTask to retrieve the data needed. The data task is supposed to perform asynchronoulsy in a thread different from main. Once finished, its completionHandler is also executed in a thread different from main. There is where I update the viewModel (see code snippet above). Then, as the model in the viewModel is being observed, an onModelChange closure is executed in the viewController, where I update a tableView with the data. Since this operation is UI related, I do it in the main thread (see also code snippet above).
Question is: this seems to work, but is it actually correct/safe to update the viewModel in a thread different from main? It was created in main thread. May this be a potential issue?
viewModel is a class, and the model it holds is an array of MyCustomModel that are structs.

Related

In Apple's Foundation/Swift/Objective-C, how does runLoop.run block, but still allow DispatchWorkItems to process?

Why does this code execute like this? Note the comments in the test code which indicate which lines pass and fail.
More specifically, how is it that RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) waits there, while still allowing for the DispatchWorkItem, { [weak self] in self?.name = newName }, to process? If the thread is waiting on the run loop, how can the thread process any work items?
(Or please correct my understanding if the question doesn't make sense).
class Person {
private(set) var name: String = ""
func updateName(to newName: String) {
DispatchQueue.main.async { [weak self] in self?.name = newName }
}
}
class PersonTests: XCTestCase {
func testUpdateName() {
let sut = Person()
sut.updateName(to: "Bob")
XCTAssertEqual(sut.name, "Bob") // Fails: `sut.name` is still `""`
assertEventually { sut.name == "Bob" } // Passes
}
}
func assertEventually(
timeout: TimeInterval = 1,
assertion: () -> Bool
) {
let timeoutDate = Date(timeIntervalSinceNow: timeout)
while Date() < timeoutDate {
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01))
if assertion() == true { return }
}
XCTFail()
}
The while loop keeps execution from proceeding, but the run command doesn’t just wait, but rather it processes events on that thread’s run loop, including the processing of GCD sources, timers, dispatched blocks, etc.
FWIW, when you're dealing with an asynchronous method, you would either:
Use completion handler.
Generally if you have an asynchronous method, in order to reason about the state of the object (e.g. when to dismiss a spinner letting the user know when it’s done), you'd supply a completion handler. (This is assuming that the simple async was a simplification of some more complicated asynchronous pattern.)
If you really want to have an asynchronous method that asynchronously mutates the object and your app doesn’t currently need to know when it’s done, then make that completion handler optional:
func updateName(to name: String, completion: (() -> Void)? = nil) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.name = name
completion?()
}
}
Then you can use expectations in your unit tests, which is the standard way of testing asynchronous methods:
func testUpdateName() {
let e = expectation(description: "Person.updateName")
let person = Person()
person.updateName(to: "Bob") {
e.fulfill()
}
waitForExpectations(timeout: 1)
XCTAssertEqual(person.name, "Bob")
}
Use a “reader”.
The previous point is a general observation about testing asynchronous methods. But if you really have a method that is asynchronously mutating an object, you generally would not expose the mutating properties directly, but rather you might use a “reader” method to fetch the property value in a general, thread-safe manner. (E.g. in reader-writer pattern, you might update asynchronously, but your reader would wait for any pending writes to finish first.)
So, consider a Person that is using the reader-writer pattern:
class Person {
// don't expose the name at all
private var name: String = ""
// private synchronization reader-writer queue
private let queue = DispatchQueue(label: "person.readerwriter", attributes: .concurrent)
// perform writes asynchronously with a barrier
func writeName(to name: String) {
queue.async(flags: .barrier) {
self.name = name
}
}
// perform reads synchronously (concurrently with respect to other reads, but synchronized with any writes)
func readName() -> String {
return queue.sync {
return name
}
}
}
Then the test would use the readName
func testUpdateName() {
let person = Person()
person.writeName(to: "Bob")
let name = person.readName()
XCTAssertEqual(name, "Bob")
}
But you generally would not have a property with asynchronous writes without some way to synchronize reads, too. The example in the question would work if used from main thread only. Otherwise, you’d have race condition.

Swift iOS ReactiveKit: calling the observer causes to trigger action multiple times?

I have Singleton class to which i have used to observe a property and trigger next action.
Singleton Class:
public class BridgeDispatcher: NSObject {
open var shouldRespondToBridgeEvent = SafePublishSubject<[String: Any]>()
open var shouldPop = SafePublishSubject<Void>()
open var shouldUpdate = SafePublishSubject<Void>()
public let disposeBag = DisposeBag()
open static let sharedInstance: BridgeDispatcher = BridgeDispatcher()
override init() {
super.init()
shouldRespondToBridgeEvent.observeNext { event in
if let type = event["type"] as? String {
switch type {
case "ShouldUpdate":
self.onShiftBlockDidUpdateHeight.next()
case "shouldPop":
self.onPopCurrentViewController.next(())
default:
print("Event not supported")
}
}
}.dispose(in: self.disposeBag)
}
}
Above method will trigger by calling:
BridgeDispatcher.sharedInstance.shouldRespondToBridgeEvent.next(body)
Register for onPopCurrentViewController:
BridgeDispatcher.sharedInstance.onPopCurrentViewController.observeNext { doSomething() }.dispose(in: BridgeDispatcher.sharedInstance.disposeBag)
On my application, BridgeDispatcher.sharedInstance.onPopCurrentViewController.observeNext{} method will be called multiple times due to the business logic, due to this doSomething() method will trigger multiple times when calling BridgeDispatcher.sharedInstance.shouldRespondToBridgeEvent.next(body).
Is this issue with my singleton design pattern or observeNext calling multiple times. (BridgeDispatcher.sharedInstance.onPopCurrentViewController.observeNext{} )
Need help.
I have used .updateSignal on ObservableComponent.
valueToUpdate.updateSignal.compactMap { (arg0) -> String? in
let (value, _, validationFailure) = arg0
return validationFailure == nil ? value?.value : nil
}
.removeDuplicates()
.debounce(for: 1.0)
.observeNext { [unowned self] _ in
self.doYourWork()
}
.dispose(in: self.bag)
It attempts to deal with the multiple calls in two ways: first by discarding any duplicate events, so if the duration hasn’t changed, then no call is made. Second, by debouncing the signal so if the user makes a bunch of changes we only call the method when they’re done making changes.

RxSwift. Execute separate Observables sequently

I'm trying to achieve my Observables to execute only when previous Observable has completed. I can't use flatMap, because subscriptions can be called from different places, and this Observables is not connected with each other. To be specific: I have my CollectionView loading more content from server and 2 seconds after that user clicks "Send comment" button while CollectionView is still loading its batch. So I want to wait until CollectionView update completes and only then execute my comment's posting request. I created a class named ObservableQueue and it's working just fine. But I need to know if it has issues like memory leaks, dead locks or maybe I just missing something. Here it is:
extension CompositeDisposable {
#discardableResult
func insert(disposeAction: #escaping () -> ()) -> DisposeKey? {
return insert(Disposables.create(with: disposeAction))
}
}
class ObservableQueue {
private let lock = NSRecursiveLock()
private let relay = BehaviorRelay(value: 0)
private let scheduler = SerialDispatchQueueScheduler(internalSerialQueueName: "ObservableQueue.scheduler")
func enqueue<T>(_ observable: Observable<T>) -> Observable<T> {
return Observable.create({ observer -> Disposable in
let disposable = CompositeDisposable()
let relayDisposable = self
.relay
.observeOn(self.scheduler)
.filter({ value -> Bool in
if value > 0 {
return false
}
self.lock.lock(); defer { self.lock.unlock() }
if self.relay.value > 0 {
return false
}
self.relay.accept(self.relay.value + 1)
disposable.insert {
self.lock.lock(); defer { self.lock.unlock() }
self.relay.accept(self.relay.value - 1)
}
return true
})
.take(1)
.flatMapLatest { _ in observable }
.subscribe { observer.on($0) }
_ = disposable.insert(relayDisposable)
return disposable
})
}
}
And then I can use it like this:
let queue = ObservableQueue()
...
// first observable
let observable1 = Observable
.just(0)
.delay(5, scheduler: MainScheduler.instance)
queue
.enqueue(observable1)
.subscribe(onNext: { _ in
print("here1")
})
.disposed(by: rx.disposeBag)
// second observable
let observable2 = Observable
.just(0)
.delay(5, scheduler: MainScheduler.instance)
queue
.enqueue(observable2)
.subscribe(onNext: { _ in
print("here2")
})
.disposed(by: rx.disposeBag)
// third observable
let observable3 = Observable
.just(0)
.delay(5, scheduler: MainScheduler.instance)
queue
.enqueue(observable3)
.subscribe(onNext: { _ in
print("here3")
})
.disposed(by: rx.disposeBag)
CLGeocoder has the same issue. According to the documentation, you can't call one of the geocoder methods while it's working on a previous request so very much like what you are trying to do. In this gist (https://gist.github.com/danielt1263/64bda2a32c18b8c28e1e22085a05df5a), you will find that I make the observable calls on a background thread and protect the job with semaphore. That's the key, you need a semaphore, not a lock.
Something like this should work for you:
class ObservableQueue {
private let semaphore = DispatchSemaphore(value: 1)
private let scheduler = ConcurrentDispatchQueueScheduler(qos: .userInitiated)
func enqueue<T>(_ observable: Observable<T>) -> Observable<T> {
let _semaphore = semaphore // To avoid the use of self in the block below
return Observable.create { observer in
_semaphore.wait()
let disposable = observable.subscribe { event in
switch event {
case .next:
observer.on(event)
case .error, .completed:
observer.on(event)
}
}
return Disposables.create {
disposable.dispose()
_semaphore.signal()
}
}
.subscribeOn(scheduler)
}
}
I will give you some suggestions that I think will help you in the future.
Avoid as much as possible the Observable.create, this is the "brute force" creation of an observable and it doesn't handle back pressure at all, you'll have to implement it yourself, and it's not something easy.
Usually for HTTP api calls, you don't need Observable, you should use Single or Completable since you expect only one response from your server, not a stream of responses.
You should be careful with strong self inside the onNext/on..., as a rule of thumb if the class that subscribes to the observer has the dispose bag, you should use a weak self.
Now for your particular case, if you need to just this pair of observers (fetch & send comment), I think the queue is a little bit overkill. You can simply call the post comment observer (if available) on the do(onNext:) method of your "fetch" observer. Do on next is called every time an "onNext" event is triggered.
If you still need a queue, I would go with an OperationQueue that enqueues only operations and has a method like observeOperationchanges() -> Observeble<Operation> this will be triggered every time an operation is completed. In this way you subscribe once and enqueue multiple times, but this might not fit your needs.
I would use .combineLatest() to produce an event once both observables have emitted something. See http://rxmarbles.com/#combineLatest

Working with Model async data and TableView

I'm creating an app and I have all the logic done, but I want to do a Code refactoring and create MVC pattern. But I dealing with some asynchronous informations, that came from API.
/MenuViewController
Alamofire.request(.GET, Urls.menu).responseJSON { request in
if let json = request.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let data = JSON(json)
var product: [Product] = []
for (_, subJson): (String, JSON) in data {
product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
}
dispatch_async(dispatch_get_main_queue()) {
self.products += product
self.tableView.reloadData()
}
}
}
}
This is my code, already working. But I want to create a Model that will handle this and just return the array of Products to my MenuViewController.
Model/Menu
class Menu {
var products: [Product] = []
init() {
Alamofire.request(.GET, Urls.menu).responseJSON { request in
if let json = request.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let data = JSON(json)
var product: [Product] = []
for (_, subJson): (String, JSON) in data {
product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
}
dispatch_async(dispatch_get_main_queue()) {
self.products += product
}
}
}
}
}
func totalOfProducts() -> Int {
return self.products.count
}
func getProducts() -> [Product]? {
return self.products
}
func getProductFromIndex(index: Int) -> Product {
return self.products[index]
}
}
But I got my self thinking, how I gonna get the main_queue to another class?
So I tried something like this:
class MenuViewControlvar: UITableViewController {
var products: [Product] = []
let menu: Menu = Menu()
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if let products = menu.getProducts() {
self.tableView.reloadData()
}
// rest of the code
But didn't worked. My TableView is never updated.
I was wondering if I can do this, or I've to keep my Alamofire code in my viewDidLoad() from my MenuViewController
Thank you.
I am just giving you a direction with the step I would follow (Not writing the code thinking you can work it out):
First, write a networking class that accepts network request along with a competition block. Completion block shall be executed as soon as networking is done. This is a wrapper class and can be used across classes.
Second, write a model class that has all the parameters necessary for view controller's functionalities/view drawing.
Third, from view controller, call the networking class. In completion block, pass the model setting, table reload code and any code to remove loading overlay/indicator. This block should get executed on main queue.
Fourth, add code to show loading overlay/indicator before you trigger networking.
Delegation is an ideal solution for this problem of updating your model data and your view based on an asynchronous network call and it’s pretty much the same technique that is implemented throughout the iOS SDK to solve the same problem. There are many benefits of delegation over observation, another viable solution.
First, move your networking code to a separate class
class NetworkingController {
Create a protocol that view controllers can conform to. This provides the loose coupling between your network operations and your views to effectively maintain separation between the MVC layers.
#protocol NetworkingControllerDelegate: class {
func menuDataDidUpdate()
}
Have the networking controller support a property for its delegate
weak var delegate: NetworkingControllerDelegate?
In summary your networking class now looks something like this:
#protocol NetworkingControllerDelegate: class {
func menuDataDidUpdate()
}
class NetworkingController {
weak var delegate: NetworkingControllerDelegate?
// Insert networking functions here.
}
Then, have your view controller conform to this protocol like so
class MenuViewController: NetworkingControllerDelegate {
and create a new network controller in your view controller
var myNetworkController = NetworkController()
and set the delegate of your network controller instance to be your view controller
myNetworkController.delegate = self
Then in your networking code, when the network request has completed and your model has been updated, make a call to the networking controller's delegate.
delegate.menuDidUpdate()
Create the implementation for this method in your view controller since it is now the delegate for your networking code.
func menuDidUpdate() {
// Update your menu.
}
This makes your view controller look something like:
class MenuViewController: NetworkingControllerDelegate {
var myNetworkController = NetworkController()
override func viewDidLoad() {
myNetworkController.delegate = self
}
// MARK: NetworkingControllerDelegate
func menuDidUpdate() {
// Update your menu.
}
}
This is just the outline of the implementation to give you the necessary information about how to proceed. Fully adapting this to your problem is up to you.

Correct placement of capture list in nested closures in swift

Where do I define captured references for nested closures in Swift?
Take this code as an example:
import Foundation
class ExampleDataSource {
var content: Any?
func loadContent() {
ContentLoader.loadContentFromSource() { [weak self] loadedContent in
// completion handler called on background thread
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.content = loadedContent
}
}
}
}
class ContentLoader {
class func loadContentFromSource(completion: (loadedContent: Any?) -> Void) {
/*
Load content from web asynchronously,
and call completion handler on background thread.
*/
}
}
In this example, [weak self] is used in both trailing closures, however the compiler is perfectly happy if I omit [weak self] from either one of the trailing closures.
So that leaves me 3 options for defining my capture list:
define captures on every nested closure leading up to the reference
define captures on the first closure only.
define captures on only the most nested closure that actually uses the reference.
My question is:
If I know that my ExampleDataSource could be nil at some point, what is the best option to go with?
It is important to note that GCD dispatch_async will NOT cause a retain cycle. In other words, when the block has finished executing, GCD will not retain any references made within the block.
The same is not true for strong references between classes, or strong references within a closure assigned to a property of an instance. Apple Documentation
That being said, in this example, the correct answer is option 2, to define captures on the first closure only.
For testing purposes I modified the code slightly:
class ExampleDataSource {
init() {
print("init()")
}
deinit {
print("deinit")
}
var content: Any?
func loadContent() {
print("loadContent()")
ContentLoader.loadContentFromSource() { [weak self] loadedContent in
dispatch_async(dispatch_get_main_queue()) {
print("loadedContent")
self?.content = loadedContent
}
}
}
}
class ContentLoader {
class func loadContentFromSource(completion: (loadedContent: Any?) -> Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
sleep(5) // thread will hang for 5 seconds
completion(loadedContent: "some data")
}
}
}
First I create, var myDataSource: ExampleDataSource? = ExampleDataSource().
Then I run myDataSource.loadContent().
Before the completion handler gets a chance to run, I set myDataSource = nil, removing all references to it.
The debug console indicates that a reference to self was not retained:
init()
loadContent()
deinit
loadedContent
Looks like we found our answer! But just for completion's sake, let's test the alternatives...
If [weak self] is instead captured on only the inner most trailing closure, GCD will retain ExampleDataSource until the block has finished executing, which explains why the debug would instead look like this:
init()
loadContent()
loadedContent
deinit
The same thing will happen if no capture list is included and we never optionally unwrapped self, although the compiler, does try to warn you!
While it isn't technically incorrect to include [weak self] captures in all trailing closures, it does detract from the readability of code and doesn't feel very 'Swift-like'.

Resources