RxSwift) Operators (1)

Havi·2021년 3월 3일
0

RxSwift 기초

목록 보기
4/14

Observable 생성

Creating Operators

Create

구현체

/**
extension ObservableType {

    /**
         Creates an observable sequence from a specified subscribe method implementation.
    
         - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
    
         - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
         - returns: The observable sequence with the specified implementation for the `subscribe` method.
         */
    public static func create(_ subscribe: @escaping (RxSwift.AnyObserver<Self.Element>) -> RxSwift.Disposable) -> RxSwift.Observable<Self.Element>
}

예제

/// AnyObserver에게 self.element를 방출 시킨 뒤
/// Disposable을 생성하여 
/// Observable<Int> 가 된다.
/// .subscribe하면 Disposable이 되고
/// disposBag에 담아야 Void가 된다.
Observable<Int>.create { observer in
            observer.onNext(1)
            observer.onNext(2)
            observer.onCompleted()

            return Disposables.create()
        }
        .subscribe(onNext: {
            print($0)
        }, onError: {
            print($0)
        }, onCompleted: {
            print("onCompleted")
        }, onDisposed: {
            print("onDisposed")
        })
        .disposed(by: disposeBag)

.just

just는 하나의 element를 받아서 그 element 타입의 observable을 return한다.

구현체

/**
     Returns an observable sequence that contains a single element.

     - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)

     - parameter element: Single element in the resulting observable sequence.
     - returns: An observable sequence containing the single specified element.
     */
    public static func just(_ element: Element) -> Observable<Element> {
        Just(element: element)
    }

예제

/// returns single element
        Observable.just(1)
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag)
/// prints 1

.of

of는 여러개의 element를 받을 수 있고, TrhreadScheduler를 지정해주지 않을 경우 현재 스케줄러에 지정된다.

구현체

extension ObservableType {

    /**
         This method creates a new Observable instance with a variable number of elements.
    
         - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
    
         - parameter elements: Elements to generate.
         - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription.
         - returns: The observable sequence whose elements are pulled from the given arguments.
         */
    public static func of(_ elements: Self.Element..., scheduler: RxSwift.ImmediateSchedulerType = CurrentThreadScheduler.instance) -> RxSwift.Observable<Self.Element>
}

예제

	Observable.of(1,2,3)
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag
        /// prints
        /// 1
        /// 2
        /// 3
        /// Int를 반환한다.
        
        Observable.of([1,2,3])
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag)
        /// prints [1,2,3]
        /// [Int]를 반환한다.
        
        Observable.of([1,2,3], [4,5,6], [7,8,9])
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag)
        /// [1, 2, 3]
        /// [4, 5, 6]
        /// [7, 8, 9]

.from

from은 [Self.Element]를 Observable의 sequence로 바꾼다.

구현체

extension ObservableType {

    /**
         Converts an array to an observable sequence.
    
         - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
    
         - returns: The observable sequence whose elements are pulled from the given enumerable sequence.
         */
    public static func from(_ array: [Self.Element], scheduler: RxSwift.ImmediateSchedulerType = CurrentThreadScheduler.instance) -> RxSwift.Observable<Self.Element>

    /**
         Converts a sequence to an observable sequence.
    
         - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
    
         - returns: The observable sequence whose elements are pulled from the given enumerable sequence.
         */
    public static func from<Sequence>(_ sequence: Sequence, scheduler: RxSwift.ImmediateSchedulerType = CurrentThreadScheduler.instance) -> RxSwift.Observable<Self.Element> where Sequence : Sequence, Self.Element == Sequence.Element
}

예제

	Observable.from([1,2,3,4,5])
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag)
            /// prints
            /// 1
            /// 2
            /// 3
            /// 4
            /// 5
            /// [Int] -> Int로 바꾼다.

Empty

Empty는 아무런 이벤트를 방출하지 않고 빈 스트림을 가지고 있다가 onComplete에 스트림을 종료시킨다.

구현체

extension ObservableType {

    /**
         Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
    
         - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
    
         - returns: An observable sequence with no elements.
         */
    public static func empty() -> RxSwift.Observable<Self.Element>
}

마블

예제

Never

Never는 아무런 아이템을 가지지 않고 종료되지도 않는다.

구현체

extension ObservableType {

    /**
         Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
    
         - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
    
         - returns: An observable sequence whose observers will never get called.
         */
    public static func never() -> RxSwift.Observable<Self.Element>
}

마블

예제

Throw

Throw는 아무런 아이템을 가지지 않고 Error와 함께 종료한다.

구현체

/**
         Returns an observable sequence that terminates with an `error`.
    
         - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
    
         - returns: The observable sequence that terminates with specified error.
         */
    public static func error(_ error: Error) -> RxSwift.Maybe<Self.Element>

마블

예제

Interval

Interval은 일정 시간마다 이벤트를 방출한다.

구현체

extension ObservableType where Self.Element : FixedWidthInteger {

    /**
         Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
    
         - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
    
         - parameter period: Period for producing the values in the resulting sequence.
         - parameter scheduler: Scheduler to run the timer on.
         - returns: An observable sequence that produces a value after each period.
         */
    public static func interval(_ period: RxSwift.RxTimeInterval, scheduler: RxSwift.SchedulerType) -> RxSwift.Observable<Self.Element>
}

마블

Range

Range는 FixedWidthInteger일 때만 사용 가능하며 Observable<Int>.range(start: 0, count: 10)을 주면 0, 1, ... 9까지 방출한다.

구현체

extension ObservableType where Self.Element : FixedWidthInteger {

    /**
         Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
    
         - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
    
         - parameter start: The value of the first integer in the sequence.
         - parameter count: The number of sequential integers to generate.
         - parameter scheduler: Scheduler to run the generator loop on.
         - returns: An observable sequence that contains a range of sequential integral numbers.
         */
    public static func range(start: Self.Element, count: Self.Element, scheduler: RxSwift.ImmediateSchedulerType = CurrentThreadScheduler.instance) -> RxSwift.Observable<Self.Element>
}

마블

repeatElement

repeatElement는 말 그대로 받은 element를 계속 방출한다.

구현체

extension ObservableType {

    /**
         Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
    
         - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
    
         - parameter element: Element to repeat.
         - parameter scheduler: Scheduler to run the producer loop on.
         - returns: An observable sequence that repeats the given element infinitely.
         */
    public static func repeatElement(_ element: Self.Element, scheduler: RxSwift.ImmediateSchedulerType = CurrentThreadScheduler.instance) -> RxSwift.Observable<Self.Element>
}

마블

Timer

Timer는 구독 후 duetime만큼의 시간 이후에 이벤트를 방출한다.

구현체

extension ObservableType where Self.Element : FixedWidthInteger {

    /**
         Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
    
         - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
    
         - parameter dueTime: Relative time at which to produce the first value.
         - parameter period: Period to produce subsequent values.
         - parameter scheduler: Scheduler to run timers on.
         - returns: An observable sequence that produces a value after due time has elapsed and then each period.
         */
    public static func timer(_ dueTime: RxSwift.RxTimeInterval, period: RxSwift.RxTimeInterval? = nil, scheduler: RxSwift.SchedulerType) -> RxSwift.Observable<Self.Element>
}

마블

profile
iOS Developer

0개의 댓글