LoginSignup
5
0

Flowと友だちになる~初対面編~

Last updated at Posted at 2023-12-05

これは ZOZO Advent Calendar 2023 シリーズ8の6日目の記事です。

対象者

Flowが初めましての方。

この記事のゴール

Flowの値の流れが理解できる。
Flowの使い方がなんとなく理解できる。

Flowとは?

・コルーチンの一種
・複数の値を順次出力できる。
・新しい値を非同期に生成して使用できるため、メインスレッドをブロックすることなく、安全にネットワークリクエストを行うことができる。
・Flowは大きく3つの役割を持っている。

⚪︎流す値を出力する
⚪︎ストリームに流れている値やストリームそのものを変更(加工)する
⚪︎流れてきた値を使用する

イメージ図(桃太郎版)
qiita_image.png

Flowってどうやって作るの?

Flow を作成するには、FlowビルダーAPIを使用する。

Kotlinの公式のサンプルコードを用いて説明する。

①フィボナッチ数列の値を順に流すFlowを生成する。

fun fibonacci(): Flow<BigInteger> = flow {
    var x = BigInteger.ZERO
    var y = BigInteger.ONE
    while (true) {
        emit(x) //ここで値を流す
        x = y.also { // xに(y += x)の値を代入する
            y += x
        }
    }
}

② ①で流されている値を収集する。

fibonacci().take(100).collect { println(it) }

先頭から100番目までの値を一気に取り出しているため、出力値は以下となる。

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120 4660046610375530309 7540113804746346429 12200160415121876738 19740274219868223167 31940434634990099905 51680708854858323072 83621143489848422977 135301852344706746049 218922995834555169026

Flowを使ってみる!

と言ってもわかりやすいサンプルコードを提示できるほどの力はまだないので、Androidの公式のドキュメントのサンプルコードを自分なりにまとめて解説します。

値を流すところはNewsRemoteDataSource

class NewsRemoteDataSource(
    private val newsApi: NewsApi,
    private val refreshIntervalMs: Long = 5000
) {
    val latestNews: Flow<List<ArticleHeadline>> = flow {
        while(true) {
            val latestNews = newsApi.fetchLatestNews()
            emit(latestNews) // Emits the result of the request to the flow
            delay(refreshIntervalMs) // Suspends the coroutine for some time
        }
    }
}

// Interface that provides a way to make network requests with suspend functions
interface NewsApi {
    suspend fun fetchLatestNews(): List<ArticleHeadline>
}

値を変更(加工)するところはNewsRepository

class NewsRepository(
    private val newsRemoteDataSource: NewsRemoteDataSource,
    private val userData: UserData
) {
    /**
     * Returns the favorite latest news applying transformations on the flow.
     * These operations are lazy and don't trigger the flow. They just transform
     * the current value emitted by the flow at that point in time.
     */
    val favoriteLatestNews: Flow<List<ArticleHeadline>> =
        newsRemoteDataSource.latestNews
            // Intermediate operation to filter the list of favorite topics
            .map { news -> news.filter { userData.isFavoriteTopic(it) } }
            // Intermediate operation to save the latest news in the cache
            .onEach { news -> saveInCache(news) }
}

値を使用するところはLatestNewsViewModelまたはviewModelの呼び出し元

class LatestNewsViewModel(
    private val newsRepository: NewsRepository
) : ViewModel() {

    init {
        viewModelScope.launch {
            // Trigger the flow and consume its elements using collect
            newsRepository.favoriteLatestNews.collect { favoriteNews ->
                // Update View with the latest favorite news
            }
        }
    }
}

値の流れがわかりやすいように図式化↓
flow_image.jpg

ViewModelからcollectされると、値を流している、NewsRemoteDataSorceから5秒間隔で最新ニュースが流れてくる。NewsRepositoryでお気に入りニュースだけが流れるようにフィルターをかけている。

DataSourceはwhile(true)で常に最新ニュースを更新しているため、ViewModelScopeをキャンセルしない限りずっと流れてくる。

DataSourceのコードを以下のように変えた場合は、DataSourceでcountが10になったら値の出力が終了するため、この場合も収集が終了します。

class NewsRemoteDataSource(
    private val newsApi: NewsApi,
    private val refreshIntervalMs: Long = 5000
) {
    var count = 0
    val latestNews: Flow<List<ArticleHeadline>> = flow {
        while(count < 10) {
            val latestNews = newsApi.fetchLatestNews()
            emit(latestNews) // Emits the result of the request to the flow
            delay(refreshIntervalMs) // Suspends the coroutine for some time
            count++
        }
    }
}

まとめ

今回は触れなかった、StateFlowやShardFlowなどなど...は別の機会で記事にまとめていこうと思います。
Flowはまだまだ奥深いので今すぐには仲良くなれそうにない。
けど仲良くなればとてもいい友だちになれそうなので、これからもFlowのことを知っていこうと思います!

参考文献

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0