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

后端 未结 8 1879
无人共我
无人共我 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:35

    Building on Dalton's answer, here is a handy extension:

    extension BehaviorRelay where Element: RangeReplaceableCollection {
        func acceptAppending(_ element: Element.Element) {
            accept(value + [element])
        }
    }
    
    0 讨论(0)
  • 2021-01-30 04:37

    I wrote this extension for replacing Variables with BehaviorRelays. You can add whatever method you need based on this pattern to migrate easily.

    public extension BehaviorRelay where Element: RangeReplaceableCollection {
    
        public func insert(_ subElement: Element.Element, at index: Element.Index) {
            var newValue = value
            newValue.insert(subElement, at: index)
            accept(newValue)
        }
    
        public func insert(contentsOf newSubelements: Element, at index: Element.Index) {
            var newValue = value
            newValue.insert(contentsOf: newSubelements, at: index)
            accept(newValue)
        }
    
        public func remove(at index: Element.Index) {
            var newValue = value
            newValue.remove(at: index)
            accept(newValue)
        }
    }
    

    Instead of Variable.value.funcName, now you write BehaviorRelay.funcName.

    The idea to use where Element: RangeReplaceableCollection clause comes from retendo's answer

    Also note that the index is of type Element.Index, not Int or whatever else.

    0 讨论(0)
提交回复
热议问题