Help us understand the problem. What is going on with this article?

RxSwift 一定間隔で1文字ずつStringを流し込む(入力する)

More than 1 year has passed since last update.

TL;DR

Stringを1文字ずつ一定間隔で、UILabelやUITextViewに流し込みたい。
「1文字ずつ」、「一定間隔で」……、これはRxが得意そうなやつだ。典型的なストリームの問題だ。
そんなこんなで実装例がなかなか見つからなかったので、考えてみました。

できあがりはこちら↓

実装例

下記の例では0.05秒間隔で1文字ずつ流し込んでいきます。

    @IBAction func didTapButton(_ sender: UIButton) {
        label.text = nil

        let lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        let text  = Observable.just(lorem)
        let timer = Observable<Int>.interval(0.05, scheduler: MainScheduler.instance)

        _ = Observable.combineLatest(timer, text)
            .takeWhile { (i, t)  in
                i < t.characters.count
            }
            .flatMapLatest { (i, t) -> Observable<String> in
                let characters = Array(t.characters)
                let character = characters[i]
                return Observable.just("\(character)")
            }
            .subscribe(onNext: { [weak self] (character) in
                let currentText = self?.label.text ?? ""
                self?.label.text = currentText + character
            })
    }

ポイントはtakeWhileです。

iが文字数以上になるとcompletedが呼ばれ、シーケンスがterminateされます。
試しにsubscribe { print($0) }に変えてみるとcompletedが呼ばれているのが確認できます。

next(L)
next(o)
next(r)
// ...
completed
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした