RxSwift pointfree style avoid retain cycles - swift

Im wondering if i can use pointfree-style using Swift/RxSwift like so:
class MyClass {
private let ageService: Observable<Int> = AgeService()
private let userService: Observable<Bool> = UserService()
func test() -> Observable<Int>{
return userService
.getRandomUser()
.flatMap(self.networkService.ageFromUser)
}
Or should i go always with .. ?
func test2() -> Observable<Int>{
return userService.getRandomUser().flatMap { [weak self] user in
guard let strongSelf = self else { return .empty() }
return strongSelf.networkService.ageFromUser(user)
}
}

When working with closures when you are pointing to self inside closure like in your case of flapmap the retain cycle gets created if you DON'T use [weak/unowned self].
So its developer responsibility to avoid these kind of retain cycles. So whenever you have reference for self inside any closure try to use weak / unowned as per scope. In your case go for second i.e test2 function.
Hope out helps ...!!!

Related

Is it required to to use weak reference's within a singleton class?

I came across a tutorial from raywenderlich were the author gave some good tips on handling threading issues in singleton. But when using closures from within the singleton class he is using 'weak' reference cycle. Is it really required so since the class is a singleton, it should have a single instance always right?
final class PhotoManager {
private init() {}
static let shared = PhotoManager()
private var unsafePhotos: [Photo] = []
let concurrentPhotoQueue = DispatchQueue(label: "com.jeesson.googlypuff.photoQueue", attributes: .concurrent)
var photos: [Photo] {
var photoCopy:[Photo]!
concurrentPhotoQueue.sync {
photoCopy = self.unsafePhotos
}
return photoCopy
}
func addPhoto(_ photo: Photo) {
// Do we need 'weak self here.. and why?
concurrentPhotoQueue.async(flags: .barrier) {[weak self] in
// 1
guard let self = self else {
return
}
self.unsafePhotos.append(photo)
DispatchQueue.main.async { [weak self] in
//self?.postContentAddedNotification()
}
}
}
}
The tutorial
In case of DispatchQueue closures don't add any capture list at all, nowhere.
DispatchQueue closures don't cause retain cycles because self doesn't own them.
Basically capture lists inside a singleton object are not needed as the singleton is never going to be deallocated.
Some singleton's lifecycle is tied to App lifecycle. Some singleton's lifecycle is tied to login/logout.
So what if the singleton is to be deallocated upon logout? I think that's a valid case where using [weak self] can be useful, even for a singleton.
Otherwise just as vadian said, DispatchQueue closures don't cause retain cycles because self doesn't own them. For more see here

Setting function-scope variable to avoid using a capture list

I have the following class, which uses a closure in one of its methods:
class SomeClass {
let someOtherClassInstance: OtherClass
func performAsyncTask() {
DispatchQueue.global(qos: .background).async { [weak self] in
print("\(self?.someOtherClassInstance)")
}
}
}
I'm wondering if I can also rewrite performAsyncTask as:
func performAsyncTask() {
let instance = self.someOtherClassInstance
DispatchQueue.global(qos: .background).async {
print("\(instance)")
}
}
The main goal is that I can avoid making self weak in the capture list - or rather so that I don't have to access self at all. There seems to be no reference to self in the second version, but is there a possibility that there will be an error when I try to access instance?
That's fine (assuming that self.someOtherClassInstance has no
back references to the SomeClass instance). You can achieve the
same with a capture list:
func performAsyncTask() {
DispatchQueue.global(qos: .background).async {
[instance = self.someOtherClassInstance] in
print("\(instance)")
}
}
The closure captures a strong reference to the
OtherClass instance which is held until it has been executed,
but no reference to self.
Note that the closure accesses instance regardless of whether
the SomeClass instance still exists or not, so the behavior is
slightly different from what your first method does.

Swift 3: capture strong self in #escaping closure without asynchronous work

There is a protocol with the following declaration:
typealias SuggestionSourceCallback = ([Suggestion]) -> ()
protocol SuggestionSource {
func suggest(_ query: SuggestionQuery, callback: #escaping SuggestionSourceCallback)
}
Two classes implement this protocol. First class obtains suggestions asynchronously (via GCD)
final class FisrtClass: SuggestionSource {
private let queue = DispatchQueue(label: "my.app.queue", attributes: [])
private var lastQuery: SuggestionQuery?
// ...
func suggest(_ query: SuggestionQuery, callback: #escaping SuggestionSourceCallback) {
self.queue.async { [weak self] in
// capturing strong self
guard let strongSelf = self else {
return
}
// referencing self here, for example
guard self.lastQuery == query else {
return
}
// suggestions is a local variable
var suggestions: [Suggestion] = []
// ...
DispatchQueue.main.async {
callback(suggestions)
}
}
}
}
...while second class does it synchronously
final class SecondClass: SuggestionSource {
// ...
func suggest(_ query: SuggestionQuery, callback: #escaping SuggestionSourceCallback) {
// ...
callback(self.suggestions[query])
}
}
My questions are:
should I capture strongSelf in FirstClass's implementation?
should I capture strongSelf in SecondsClass's implementation?
UPDATE
Additional question. Suppose SecondClass has its suggestions as a static let, what pattern in this case would be?
final class SecondClass: SuggestionSource {
static let suggestions: [String: [SuggestionQuery]] = {
// ...
}()
// ...
func suggest(_ query: SuggestionQuery, callback: #escaping SuggestionSourceCallback) {
// ...
callback(self.suggestions[query])
}
}
In SecondClass, there is no need to create a strongSelf variable. Where would you put it? The point is that self is guaranteed not to be nil anyway because you are running within the scope of one of its methods.
The same is true of your additional question, but for a different reason. suggestions is now static, so prefixing with self is a matter of syntax, (I am presuming you meant to also prefix the suggest method with static).
However, in FirstClass, there is a subtle difference between capturing strongSelf and not capturing it.
Because you are using [weak self], self could be nil when you enter that block so you need to check against that anyway. One way is to repeatedly use optional chaining, i.e.:
self?.doSomething()
self?.doSomethingElse()
This is saying:
If I have a reference to self, do something. If I still have a
reference to self, do something else.
By adding a strongSelf variable:
guard let strongSelf = self else {
return
}
strongSelf.doSomething()
strongSelf.doSomethingElse()
...you are saying:
do something and do something else if you have a reference to self,
otherwise do nothing.
So, you guarantee that if the first thing happens, so does the second. The approach you take is going to depend on your application.
Scenario 1 is a good candidate for [unowned self].
In this case if the queue exists, so does self, therefore it is safe to reference self without retaining it.
Note: You should only use unowned when you can be sure that the block's lifecycle is directly tied to the captured variable. In other cases unowned can cause interrmittent crashes (which are really hard to debug).
Also unowned is more performant than weak so should be preferred where it is safe to use either source.
For scenario 2, self is not captured by any block that I can determine so you shouldn't need to worry at all about it.
For the update, you still don't capture self, the closure that defines the suggestions dictionary should be executed as soon as it is called.

Why isn't self automatically declared as unowned in blocks?

Up till now, I've been naïvely using Swift without really caring about the memory management. But I'm implementing a capture list, and I guess it sort of makes sense.
My question is - why wouldn't self be automatically made unowned to avoid retain cycles? Is there a situation in which you'd explicitly need self to be owned that couldn't be resolved by saving some of its data elsewhere?
Give you a simple example
This is a class that I need to use self,not unowned self
If I use self here
class Test{
func log(){
println("log");
}
func FunctionHaveBlock(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
() -> Void in
sleep(4)
self.log()
})
}
deinit{
println("Deinit")
}
}
Then call
var test:Test? = Test()
test!.FunctionHaveBlock();
test = nil;
The code will executed well,after 4 seconds,it will log
log
Deinit
But if I changed to unowned self,
class Test{
func log(){
println("log");
}
func FunctionHaveBlock(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
[unowned self]
() -> Void in
sleep(4)
self.log()
})
}
deinit{
println("Deinit")
}
}
Then call
var test:Test? = Test()
test!.FunctionHaveBlock();
test = nil;
It will log
Deinit
then After 4 seconds,the app crashed.Because,the object is dealloced.
So,if you need to retain the object,you do not use unowned self

Strong Reference Cycles for Closures?

Swift Closure will have a strong reference cycle when it refers to self like this example:
class Test {
var name = "Hello"
func doSomething() {
{() -> Void in
self.name = "otherName"
}()
}
}
In the previous example, I created a strong reference cycle so I have to fix it with:
class Test {
var name = "Hello"
func doSomething() {
{[unowned self] () -> Void in
self.name = "otherName"
}()
}
}
Question: If I refer self in a closure do I have to use alway unowned self or are there cases where I have to use weak self?
If I refer self in a closure do I have to use alway unowned self or are there cases where I have to use weak self?
Neither. In most cases, just refer to self normally and do nothing with its memory management. You only have to worry about memory management if there is a danger of a retain cycle, and unless you store the closure somewhere, such as a property of self, there is no such danger.
You can easily prove this by adding a deinit implementation:
class Test {
var name = "Hello"
func doSomething() {
{() -> Void in
self.name = "otherName"
}()
}
deinit {
println("bye")
}
}
Now make a Test instance and immediately release it:
func testTest () {
let t = Test()
}
You see "bye" in the console, proving that the instance was released in good order. There was never any kind of "strong reference cycle" in this code. Your concerns are groundless.
[By the way, you are using the word "closure" wrong. Every Swift function is a closure. If there were a retain cycle issue merely because of using the word self in a closure, every Swift function would be subject to this issue - and clearly that is not the case. The place where weak and unowned self comes into play is in an anonymous function - and only, as I said before, if that anonymous function is itself also retained by self.]