How to use BehaviorRelay as an alternate to Variable in RxSwift?

后端 未结 8 1892
无人共我
无人共我 2021-01-30 03:52

As of RxSwift4, Variable is moved to Deprecated.swift marking the possible deprecation of Variable in future. An alternate proposed to

8条回答
  •  悲哀的现实
    2021-01-30 04:34

    I created those this extension, with two methods to facilitate migration in case you have a Variable of Array and you have to use append.

        extension BehaviorRelay where Element: RangeReplaceableCollection {
    
            func append(_ subElement: Element.Element) {
                var newValue = value
                newValue.append(subElement)
                accept(newValue)
            }
    
            func append(contentsOf: [Element.Element]) {
                var newValue = value
                newValue.append(contentsOf: contentsOf)
                accept(newValue)
            }
    
            public func remove(at index: Element.Index) {
                var newValue = value
                newValue.remove(at: index)
                accept(newValue)
            }
    
            public func removeAll() {
                var newValue = value
                newValue.removeAll()
                accept(newValue)
            }
    
        }
    

    and you call it like this

        var things = BehaviorRelay<[String]>(value: [])
        things.append("aa")
        let otherThings = ["bb", "cc"]
        things.append(contentsOf: otherThings) 
        things.remove(at: 0)
        things.removeAll()
    

提交回复
热议问题