RxSwift. Execute separate Observables sequently - ios

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

Related

How to wrap the delegate pattern with a one-shot publisher?

Normally we can bridge our async code and Combine by wrapping our async code in a single-shot publisher using a Future:
func readEmail() -> AnyPublisher<[String], Error> {
Future { promise in
self.emailManager.readEmail() { result, error in
if let error = error {
promise(.failure(error))
} else {
promise(.success(result))
}
}
}.eraseToAnyPublisher()
}
On the other hand, if we're wrapping the delegate pattern (instead of an async callback), it's recommended to use a PassthroughSubject, since the methods could be fired multiple times:
final class LocationHeadingProxy: NSObject, CLLocationManagerDelegate {
private let headingPublisher: PassthroughSubject<CLHeading, Error>
override init() {
headingPublisher = PassthroughSubject<CLHeading, Error>()
// ...
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
headingPublisher.send(newHeading)
}
}
However, I'm trying to create a one-shot publisher which wraps an existing Delegate pattern. The reason is that I'm firing off a method like connect() and I expect either a success or failure to happen immediately. I do not want future updates to affect the pipeline.
For example, imagine I'm using WKExtendedRuntimeSession and wrapped the .start() method in startSession() below. If I have this wrapped successfully, I should be able to use it like so:
manager.startSession()
.sink(
receiveCompletion: { result in
if result.isError {
showFailureToStartScreen()
}
},
receiveValue: { value in
showStartedSessionScreen()
})
.store(in: &cancellables)
The reason a one-shot publisher is useful is because we expect one of the following two methods to be called soon after calling the method:
Success: extendedRuntimeSessionDidStart(_:)
Fail: extendedRuntimeSession(_:didInvalidateWith:error:)
Furthermore, when the session is halted (or we terminate it ourselves), we don't want side effects such as showFailureToStartScreen() to randomly happen. We want them to be handled explicitly elsewhere in the code. Therefore, having a one-shot pipeline is beneficial here so we can guarantee that sink is only called once.
I realize that one way to do this is to use a Future, store a reference to the Promise, and call the promise at a later time, but this seems hacky at best:
class Manager: NSObject, WKExtendedRuntimeSessionDelegate {
var session: WKExtendedRuntimeSession?
var tempPromise: Future<Void, Error>.Promise?
func startSession() -> AnyPublisher<Void, Error> {
session = WKExtendedRuntimeSession()
session?.delegate = self
return Future { promise in
tempPromise = promise
session?.start()
}.eraseToAnyPublisher()
}
func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
tempPromise?(.success(()))
tempPromise = nil
}
func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession, didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?) {
if let error = error {
tempPromise?(.failure(error))
}
tempPromise = nil
}
}
Is this really the most elegant way to work with delegates + one-shot publishers, or is there a more elegant way to do this in Combine?
For reference, PromiseKit also has a similar API to Future.init. Namely, Promise.init(resolver:). However, PromiseKit also seems to natively support the functionality I describe above with their pending() function (example):
func startSession() -> Promise {
let (promise, resolver) = Promise.pending()
tempPromiseResolver = resolver
session = WKExtendedRuntimeSession()
session?.delegate = self
session?.start()
return promise
}
You can ensure a one-shot publisher with .first() operator:
let subject = PassthroughSubject<Int, Never>()
let publisher = subject.first()
let c = publisher.sink(receiveCompletion: {
print($0)
}, receiveValue: {
print($0)
})
subject.send(1)
subject.send(2)
The output would be:
1
finished

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 trigger observable execution

I have a Subject observable representing the result of the network request that needs to be delivered to multiple subscribers.
I can use ReplaySubject of buffer 1 and publish() method. However, the network request gets executed only once.
I'd like to trigger the fetch event at any give point in the future. How can I trigger a new requst?
Currently, I have a Service object that holds the ReplaySubject and has a method reload() which triggers the network request and publishes the result to the aReplaySubject.
Is there any method on Observable that can "refresh" it and deliver a new value to all the current subscribers?
If I'm interpreting this question correctly, this is a fairly common problem in RxSwift. You need to be able to recreate your network request Observable each time your fetch is "triggered," but you need these results delivered on a single Observable that only gets created once, and has multiple subscribers. This is done with a flatMap:
struct Service {
var resultsObservable: Observable<Results> {
return resultsSubject.asObservable()
}
private let resultsSubject: ReplaySubject<Results> = .create(bufferSize: 1)
private let reloadSubject = PublishSubject<Void>()
private let disposeBag = DisposeBag()
init() {
bindFetch()
}
func reload() {
reloadSubject.onNext(())
}
private func bindFetch() {
reloadSubject
.asObservable()
.flatMap(fetch)
.bind(to: resultsSubject)
.disposed(by: disposeBag)
}
private func fetch() -> Observable<Results> {
// URLSession just one example
let urlRequest = URLRequest(url: URL(string: "https://apple.com")!)
return URLSession
.shared
.rx
.data(request: urlRequest)
.map(Results.init)
.catchErrorJustReturn(Results.empty())
}
}
In this example, you can subscribe to resultsObservable multiple times, and each should be updated after a new reload() occurs.

Unit-test RxSwift observable in ViewController

I'm quite new to RxSwift. I have a view controller that has a typeahead/autocomplete feature (i.e., user types in a UITextField and as soon as they enter at least 2 characters a network request is made to search for matching suggestions). The controller's viewDidLoad calls the following method to set up an Observable:
class TypeaheadResultsViewController: UIViewController {
var searchTextFieldObservable: Observable<String>!
#IBOutlet weak var searchTextField: UITextField!
private let disposeBag = DisposeBag()
var results: [TypeaheadResult]?
override func viewDidLoad() {
super.viewDidLoad()
//... unrelated setup stuff ...
setupSearchTextObserver()
}
func setupSearchTextObserver() {
searchTextFieldObservable =
self.searchTextField
.rx
.text
.throttle(0.5, scheduler: MainScheduler.instance)
.map { $0 ?? "" }
searchTextFieldObservable
.filter { $0.count >= 2 }
.flatMapLatest { searchTerm in self.search(for: searchTerm) }
.subscribe(
onNext: { [weak self] searchResults in
self?.resetResults(results: searchResults)
},
onError: { [weak self] error in
print(error)
self?.activityIndicator.stopAnimating()
}
)
.disposed(by: disposeBag)
// This is the part I want to test:
searchTextFieldObservable
.filter { $0.count < 2 }
.subscribe(
onNext: { [weak self] _ in
self?.results = nil
}
)
.disposed(by: disposeBag)
}
}
This seems to work fine, but I'm struggling to figure out how to unit test the behavior of searchTextFieldObservable.
To keep it simple, I just want a unit test to verify that results is set to nil when searchTextField has fewer than 2 characters after a change event.
I have tried several different approaches. My test currently looks like this:
class TypeaheadResultsViewControllerTests: XCTestCase {
var ctrl: TypeaheadResultsViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
ctrl = storyboard.instantiateViewController(withIdentifier: "TypeaheadResultsViewController") as! TypeaheadResultsViewController
}
override func tearDown() {
ctrl = nil
super.tearDown()
}
/// Verify that the searchTextObserver sets the results array
/// to nil when there are less than two characters in the searchTextView
func testManualChange() {
// Given: The view is loaded (this triggers viewDidLoad)
XCTAssertNotNil(ctrl.view)
XCTAssertNotNil(ctrl.searchTextField)
XCTAssertNotNil(ctrl.searchTextFieldObservable)
// And: results is not empty
ctrl.results = [ TypeaheadResult(value: "Something") ]
let tfObservable = ctrl.searchTextField.rx.text.subscribeOn(MainScheduler.instance)
//ctrl.searchTextField.rx.text.onNext("e")
ctrl.searchTextField.insertText("e")
//ctrl.searchTextField.text = "e"
do {
guard let result =
try tfObservable.toBlocking(timeout: 5.0).first() else {
return }
XCTAssertEqual(result, "e") // passes
XCTAssertNil(ctrl.results) // fails
} catch {
print(error)
}
}
Basically, I'm wondering how to manually/programmatically fire an event on searchTextFieldObservable (or, preferably, on the searchTextField) to trigger the code in the 2nd subscription marked "This is the part I want to test:".
The first step is to separate the logic from the effects. Once you do that, it will be easy to test your logic. In this case, the chain you want to test is:
self.searchTextField.rx.text
.throttle(0.5, scheduler: MainScheduler.instance)
.map { $0 ?? "" }
.filter { $0.count < 2 }
.subscribe(
onNext: { [weak self] _ in
self?.results = nil
}
)
.disposed(by: disposeBag)
The effects are only the source and the sink (another place to look out for effects is in any flatMaps in the chain.) So lets separate them out:
(I put this in an extension because I know how much most people hate free functions)
extension ObservableConvertibleType where E == String? {
func resetResults(scheduler: SchedulerType) -> Observable<Void> {
return asObservable()
.throttle(0.5, scheduler: scheduler)
.map { $0 ?? "" }
.filter { $0.count < 2 }
.map { _ in }
}
}
And the code in the view controller becomes:
self.searchTextField.rx.text
.resetResults(scheduler: MainScheduler.instance)
.subscribe(
onNext: { [weak self] in
self?.results = nil
}
)
.disposed(by: disposeBag)
Now, let's think about what we actually need to test here. For my part, I don't feel the need to test self?.results = nil or self.searchTextField.rx.text so the View controller can be ignored for testing.
So it's just a matter of testing the operator... There's a great article that recently came out: https://www.raywenderlich.com/7408-testing-your-rxswift-code However, frankly I don't see anything that needs testing here. I can trust that throttle, map and filter work as designed because they were tested in the RxSwift library and the closures passed in are so basic that I don't see any point in testing them either.
The problem is that self.ctrl.searchTextField.rx.text.onNext("e") won't trigger searchTextFieldObservable onNext subscription.
The subscription is also not triggered if you set the text value directly like this self.ctrl.searchTextField.text = "e".
The subscription will trigger (and your test should succeed) if you set the textField value like this: self.ctrl.searchTextField.insertText("e").
I think the reason for this is that UITextField.rx.text observes methods from UIKeyInput.
I prefer to keep UIViewControllers far away from my unit tests. Therefore, I suggest moving this logic to a view model.
As your bounty explanation details, basically what you are trying to do is mock the textField's text property, so that it fires events when you want it to. I would suggest replacing it with a mock value altogether. If you make textField.rx.text.bind(viewModel.query) the responsibility of the view controller, then you can focus on the view model for the unit test and manually alter the query variable as needed.
class ViewModel {
let query: Variable<String?> = Variable(nil)
let results: Variable<[TypeaheadResult]> = Variable([])
let disposeBag = DisposeBag()
init() {
query
.asObservable()
.flatMap { query in
return query.count >= 2 ? search(for: $0) : .just([])
}
.bind(results)
.disposed(by: disposeBag)
}
func search(query: String) -> Observable<[TypeaheadResult]> {
// ...
}
}
The test case:
class TypeaheadResultsViewControllerTests: XCTestCase {
func testManualChange() {
let viewModel = ViewModel()
viewModel.results.value = [/* .., .., .. */]
// this triggers the subscription, but does not trigger the search
viewModel.query.value = "1"
// assert the results list is empty
XCTAssertEqual(viewModel.results.value, [])
}
}
If you also want to test the connection between the textField and the view model, UI tests are a much better fit.
Note that this example omits:
Dependency injection of the network layer in the view model.
The binding of the view controller's textField value to query (i.e., textField.rx.text.asDriver().drive(viewModel.query)).
The observing of the results variable by the view controller (i.e., viewModel.results.asObservable.subscribe(/* ... */)).
There might be some typos in here, did not run it past the compiler.
If you look at the underlying implementation for rx.text, you'll see it relies on controlPropertyWithDefaultEvents which fires the following UIControl events: .allEditingEvents and .valueChanged.
Simply setting the text, it won't fire any events, so your observable is not triggered. You have to send an action explicitly:
textField.text = "Something"
textField.sendActions(for: .valueChanged) // or .allEditingEvents
If you are testing within a framework, sendActions won't work because the framework is missing the UIApplication. You can do this instead
extension UIControl {
func simulate(event: UIControl.Event) {
allTargets.forEach { target in
actions(forTarget: target, forControlEvent: event)?.forEach {
(target as NSObject).perform(Selector($0))
}
}
}
}
...
textField.text = "Something"
textField.simulate(event: .valueChanged) // or .allEditingEvents

Resources