[转] Combine学习笔记 - Cancellation & Memory Management

参考链接: https://github.com/AvdLee/CombineSwiftPlayground

5天前 8次点击 来自 移动端

标签: Swift

Cancellation

A subscription returns a Cancellable object

Correct memory management using Cancellable makes sure you're not retaining any references.

本小节讲述的是内存管理,正确的使用Cancellable

import Foundation
import Combine
import UIKit

/*:
# Cancellation
A subscription returns a `Cancellable` object

Correct memory management using `Cancellable` makes sure you're not retaining any references.
*/

class MyClass {
	var cancellable: Cancellable? = nil
	var variable: Int = 0 {
		didSet {
			print("MyClass object.variable = \(variable)")
		}
	}

	init(subject: PassthroughSubject<Int,Never>) {
		cancellable = subject.sink { value in
			// Note that we are introducing a retain cycle on `self`
			// on purpose, by not using `weak` or `unowned`
			self.variable += value
		}
	}

	deinit {
		print("MyClass object deallocated")
	}
}

func emitNextValue(from values: [Int], after delay: TimeInterval) {
	DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
		var array = values
		subject.send(array.removeFirst())
		if !array.isEmpty {
			emitNextValue(from: array, after: delay)
		}
	}
}

let subject = PassthroughSubject<Int,Never>()
var object: MyClass? = MyClass(subject: subject)

emitNextValue(from: [1,2,3,4,5,6,7,8], after: 0.5)

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
	print("Nullify object")
	//: **TODO** uncomment the next line to see the change
	object?.cancellable = nil
	object = nil
}

输出

MyClass object.variable = 1
MyClass object.variable = 3
MyClass object.variable = 6
Nullify object
MyClass object deallocated

如果注释掉以下两行

//    object?.cancellable = nil
//	object = nil

输出

MyClass object.variable = 1
MyClass object.variable = 3
MyClass object.variable = 6
Nullify object
MyClass object.variable = 10
MyClass object.variable = 15
MyClass object.variable = 21
MyClass object.variable = 28
MyClass object.variable = 36

以上演示的主要知识点是如何使用 Cancellable 终止订阅

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1