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

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

提交回复
热议问题