Variables

Variables represent some observable state. Variable without containing value can't exist because initializer requires initial value.

Variable wraps a Subject. More specifically it is a BehaviorSubject. Unlike BehaviorSubject, it only exposes value interface, so variable can never terminate or fail.

It will also broadcast its current value immediately on subscription.

After variable is deallocated, it will complete the observable sequence returned from .asObservable().

let variable = Variable(0)

print("Before first subscription ---")

_ = variable.asObservable()
    .subscribe(onNext: { n in
        print("First \(n)")
    }, onCompleted: {
        print("Completed 1")
    })

print("Before send 1")

variable.value = 1

print("Before second subscription ---")

_ = variable.asObservable()
    .subscribe(onNext: { n in
        print("Second \(n)")
    }, onCompleted: {
        print("Completed 2")
    })

variable.value = 2

print("End ---")

will print

Before first subscription ---
First 0
Before send 1
First 1
Before second subscription ---
Second 1
First 2
Second 2
End ---
Completed 1
Completed 2

results matching ""

    No results matching ""