Files
divkit/client/ios/Core/Base/ObservableVariable.swift
T
divkit-github f1563c9890 chore(html-reporter): up version
Initial commit

Add notification for divkit

Allow overwrite for migration

[migration] browser/bitbucket/personal/booster/divkit

Note: mandatory check (NEED_CHECK) was skipped

DivKit files moved

dIVKIT-0: Fix ts builder build

update div-gallery visibility screenshots

update div-gallery visibility screens

a.yaml cleanup

updated codegen scripts

change gallery alignment

change internal types in expressions

removed copyrights

remove permissions

TemplatesSupportTests refactoring

Ничего не поменялось. Отрефакторил и почистил тесты.

Split package.json

send all public

removed yandex-team links

URL added type as ArgumentType

added camera permission description

safe area insets for errors count view

`EdgeInsets` for debug view with errors count. Needed for fullscreen divs. Naming corresponds to mapping `EdgeInsets` to div-variables.

Will be used here: https://nda.ya.ru/t/Lhr5Lxgb5KN6nX

fixed compiler warnings

fix DivKitComponents variables setup, add update func

fix DivKitComponents variables setup, add update func

authors clean up

Удалил коллег из инфраструктуры, тестирования и мессенджера. Половину людей я вообще тут не знаю. Список какой-то косячный, в нём, например, @booster и @askvortsov нет. Предлагаю заново вручную составить и записать туда тех, кто точно дивкитом занимался, а не просто мимо проходил.

Fix DivKit pods compilability

Fix DivKit pods compilability

use only english in demo app

translate divKit demo app russian text

Scroll when keyboard opened

Scroll when keyboard opened

Fix gallery scroll in a11y

Это копия пр-а, который я делал в репо алискита:

https://bitbucket.browser.yandex-team.ru/projects/ML/repos/mobile-alice-library-android/pull-requests/18808/overview

authors clean up2

SwiftGenerator

flake8 errors fix & ya.make edit

swift generation tests

swift references

swift generator implementation

init swift generator

code refactoring
1) rename to modeling
2) rename kind to PropertyType
3) delete apply_pluralization_rules
4) description default value is empty string
5) remove entity_type_field_alias, typename_alias, client_optional, profileEntities, ignore_properties, generate_plain_constructor
6) remove client prefix

Add XcodeBuild in ignore

Add XcodeBuild in ignore

introduce new global variable api

introduce new global variable api

Revert commit bdcbc0081395ebe44ed7fe24bf5f4b25569c6df0

LayoutKitSnapshotTests

Fix sandboxRelease dependencies.

support zero value for width and height

remove unused css variables

"CONTRIBUTING.md"

README draft

updated gitignore/arcignore

introduce color type in expressions

introduce color type in expressions

added xcconfig files

fixed swift formatting

fail tests if updating references

Чтобы уж точно не забыть вернуть False.

Layout changes

Fix expression parsing

don't change clickable state in a11y

don't change clickable state in a11y

Update items checks

Parse description references to translations

add licence file link

fixed expression properties generation

add ability to track requests to global variables

Добавляем в GlobalVariableController возможность подписаться на запросы к глобальным переменным.
Нужно дляОткрыт Накопительная палитра , а так же в целом полезная функциональность, через которую можно делать ленивый прогрев глобальных переменных

Changelog

Minor fixes

bump divkit version up to 3.0.0

fixed snapshot tests depdendencies

Иногда не запускалась сборка SnapshotTestsHostApp перед стартом тестов.

used new api-generator

deserialization refactoring

removed gitignore

samples text fixes

fixed samples text

remove theme button

remove theme button

demo activity redesign

demo activity redesign

habr sample app

change deleted images in screenshot tests

change deleted images in screenshot tests

new ic_launcher

new ic_launcher

more readme

Binding variable for div input

Biding variable for div input

Implement documentation generator

Rename max_lines to max_visible_lines

Rename max_lines to max_visible_lines

add habr and medium

fix div-functions doc

Fix link in description

Text selecting for demo app enabled

Text selecting for demo app enabled

KotlinGenerator

kotlin code generation

kotlin generation tests

kotlin generation references

add gradle wrapper to kotlin json builder

add gradle wrapper to kotlin json builder

DemoApp redesign

fixed codegen scripts

debugView safeAreaInsets

DebugView safe area insets

TypeScript Generator

ya.make changes

TypeScript generator

TypeScript tests

TypeScript test references

fix enumeration aliases

debugInfoParams fix compile

Fix black box flicker in video-custom

Fixed stub image showing by moving it away from PlayerView.
Increased stub loading speed by adding VideoViewModel warmup.
Fixed redundant redraws by combining stub visibility and
bitmap data.
PlayerView background was set to transparent.

DivExpression fix

DivExpression fix

Implement translations

Save & share

bind globalVariableController to divContext

bind variableController to divContext

used new TypeScript generator

Подключил генератор на питоне. Изменения в сгенерированных файлах связаны в основном с переводом описаний на английский язык.

moved LivePreview

Перенёс LivePreview из отдельного модуля в DivKitDemoApp. Добавил сканер кодов в UrlInputView. Удалил часть дублирующегося кода.

remove sms and phone_state permission

fix links interception

fix links interception

Fix link in documentation

remove site from "config.stable.json"

Support highlight_color and keyboardType in div input

Support highlight_color in div input

Action animation fix for iOS
2022-08-25 21:21:49 +03:00

268 lines
7.7 KiB
Swift

// Copyright 2018 Yandex LLC. All rights reserved.
import Foundation
@dynamicMemberLookup
@propertyWrapper
public struct ObservableVariable<T> {
private let getter: () -> T
public let newValues: Signal<T>
// Obsolete. Do not use in new code.
// For class variables consider:
// private let observableXXXXStorage = ObservableProperty<T>
// var observableXXXX { observableXXXXStorage.asObservableVariable() }
// For adapters consider:
// init(initialValue: T, newValues: Signal<T>)
public init(getter: @escaping () -> T, newValues: Signal<T>) {
self.getter = getter
self.newValues = newValues
}
public var wrappedValue: T { getter() }
public var projectedValue: Self { self }
public subscript<U>(dynamicMember path: KeyPath<T, U>) -> ObservableVariable<U> {
map { $0[keyPath: path] }
}
public subscript<ValueType, UnderlyingType>(
dynamicMember path: KeyPath<UnderlyingType, ValueType>
) -> ObservableVariable<ValueType?> where T == UnderlyingType? {
map { $0?[keyPath: path] }
}
public subscript<ValueType, UnderlyingType>(
dynamicMember path: KeyPath<UnderlyingType, ValueType?>
) -> ObservableVariable<ValueType?> where T == UnderlyingType? {
map { $0?[keyPath: path] }
}
}
extension ObservableVariable {
public var value: T {
getter()
}
public func asVariable() -> Variable<T> {
Variable(getter)
}
public static func constant(_ value: T) -> ObservableVariable {
ObservableVariable(getter: { value }, newValues: .empty)
}
public var currentAndNewValues: Signal<T> {
newValues.startWith(getter)
}
public var oldAndNewValues: Signal<(old: T?, new: T)> {
var oldValue = self.getter()
return Signal<(old: T?, new: T)>(addObserver: { observer in
self.newValues.addObserver { newValue in
observer.action((old: oldValue, new: newValue))
oldValue = newValue
}
}).startWith { (old: nil, new: self.getter()) }
}
public func map<U>(_ transform: @escaping (T) -> U) -> ObservableVariable<U> {
ObservableVariable<U>(
getter: compose(transform, after: getter),
newValues: newValues.map(transform)
)
}
public func cachedMap<U>(_ transform: @escaping (T) -> U) -> ObservableVariable<U> {
var current = transform(value)
let pipe = SignalPipe<U>()
let token = newValues.addObserver {
current = transform($0)
pipe.send(current)
}
return ObservableVariable<U>(
getter: { current },
newValues: Signal(addObserver: { observer in
let outerToken = pipe.signal.addObserver(observer)
return Disposable {
withExtendedLifetime(token) { outerToken.dispose() }
}
})
)
}
public func flatMap<U>(_ transform: @escaping (T) -> ObservableVariable<U>)
-> ObservableVariable<U> {
let newValues = self.newValues
.map { transform($0).currentAndNewValues }
.startWith { [getter] in transform(getter()).newValues }
.flatMap { $0 }
return ObservableVariable<U>(
getter: { [getter] in transform(getter()).getter() },
newValues: newValues
)
}
public func compactMap<U>(
valueIfNil: @autoclosure () -> U,
_ transform: @escaping (T) -> U?
) -> ObservableVariable<U> {
ObservableVariable<U>(
initialValue: transform(value) ?? valueIfNil(),
newValues: newValues.compactMap(transform)
)
}
public func skipRepeats(areEqual: @escaping (T, T) -> Bool) -> ObservableVariable {
ObservableVariable(
getter: getter,
newValues: newValues.skipRepeats(areEqual: areEqual, initialValue: getter)
)
}
public var lazy: ObservableVariable<Lazy<T>> {
ObservableVariable<Lazy<T>>(
getter: { Lazy(getter: { self.value }) },
newValues: newValues.map { Lazy(value: $0) }
)
}
public func involving(_ signals: Signal<T>...) -> Self {
involving(signals)
}
public func involving(_ signals: [Signal<T>]) -> Self {
Self(initialValue: value, newValues: .merge([newValues] + signals))
}
}
extension ObservableVariable where T: Equatable {
public func skipRepeats() -> ObservableVariable {
skipRepeats(areEqual: ==)
}
}
extension ObservableVariable {
public func assertingMainThread() -> ObservableVariable {
ObservableVariable(
getter: { [getter] in
Thread.assertIsMain()
return getter()
},
newValues: newValues.assertingMainThread()
)
}
public static func keyPath<Root: NSObject>(
_ keyPath: KeyPath<Root, T>,
onNSObject object: Root
) -> ObservableVariable {
let newValues = Signal.changesForKeyPath(keyPath, onNSObject: object, options: .new)
.compactMap { $0.change.newValue }
return ObservableVariable(
getter: { object[keyPath: keyPath] },
newValues: newValues
)
}
}
extension ObservableVariable {
public static func `nil`<U>() -> ObservableVariable where T == U? {
ObservableVariable(getter: { nil }, newValues: .empty)
}
}
extension ObservableVariable: ExpressibleByBooleanLiteral where T == Bool {
public init(booleanLiteral value: Bool) {
self = .constant(value)
}
}
extension ObservableVariable {
/// This initializer stores the initial and intermediate values in the underlying storage
/// Lifetime managment:
/// `newValues: Signal<T>` is not retained
/// `Disposable` of `newValues.addObserver()` is retained
public init(initialValue: T, newValues: Signal<T>) {
var value = initialValue
let pipe = SignalPipe<T>()
let subscription = newValues.addObserver {
value = $0
pipe.send($0)
}
// keeps `subscription` alive as long as the `getter` is alive
// to keep underlying `value` being updated regardless of losing
// the `ObservableVariable.newValues`
let getter: () -> T = {
withExtendedLifetime(subscription) { value }
}
// keeps `subscription` alive as long as the `newValues` signal is alive
// to keep receiving update events regardless of losing
// the `ObservableVariable.getter`
let newValues = pipe.signal.retaining(object: subscription)
self.init(
getter: getter,
newValues: newValues
)
}
}
extension ObservableVariable {
public func retaining<U>(_ object: U) -> Self {
Self(initialValue: value, newValues: newValues.retaining(object: object))
}
// if we draw analogy with array, this method makes something like this
// [nil, nil, 1, 2, 3, nil, nil, 4, 5, nil] -> [nil, [1, 2, 3], nil, [4, 5], nil]
public func collapseNils<U>() -> ObservableVariable<ObservableVariable<U>?> where T == U? {
@ObservableProperty
var outer: ObservableVariable<U>? = nil
var inner: ObservableProperty<U>?
let subscription = currentAndNewValues.addObserver { state in
guard let state = state else {
if inner != nil {
outer = nil
inner = nil
}
return
}
if let inner = inner {
inner.value = state
} else {
let localInner = ObservableProperty(initialValue: state)
outer = localInner.asObservableVariable()
inner = localInner
}
}
return $outer.retaining(subscription)
}
}
extension ObservableVariable {
public func multiplexed() -> (variable: Self, afterUpdateSignal: Signal<T>) {
var value = value
let afterUpdatePipe = SignalPipe<T>()
let pipe = SignalPipe<T>()
let subscription = newValues.addObserver {
value = $0
pipe.send($0)
afterUpdatePipe.send($0)
}
let getter: () -> T = {
withExtendedLifetime(subscription) { value }
}
let newValues = pipe.signal.retaining(object: subscription)
let modelVariable = ObservableVariable(getter: getter, newValues: newValues)
return (variable: modelVariable, afterUpdateSignal: afterUpdatePipe.signal)
}
}