๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿค2024 ์•ˆ๋“œ๋กœ์ด๋“œ/๐Ÿฟ ์˜ํ™” ํ”„๋กœ์ ํŠธ ๊ฐœ๋ฐœ ์ผ์ง€

์—ฌ๋Ÿฌ ๊ฐœ์˜ flow์„ combine์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๊ธฐ

by hyeonha 2024. 7. 5.

๋ชฉ์ฐจ

    Combine์œผ๋กœ ์—ฌ๋Ÿฌ flow ์ฒ˜๋ฆฌํ•˜๊ธฐ

    ๋ฆฌ์‚ฌ์ดํด๋Ÿฌ๋ทฐ์— ๋ณด์—ฌ์ค„ ์•„์ดํ…œ์€ ์—ฌ๋Ÿฌ api ์‘๋‹ต๊ฐ’์„ ์กฐํ•ฉํ•ด์„œ ๋งŒ๋“ค์–ด์•ผํ•œ๋‹ค.

    ์ข‹์•„์š” ์ƒํƒœ ๊ฐ’์„ likeRepository์˜ checkLikeํ•จ์ˆ˜๋กœ ๋ถ€ํ„ฐ ๋ฐ›๊ณ  emit ํ•ด์ฃผ๋Š” flow๋ฅผ ์ž‘์„ฑํ•ด์ค€ ํ›„ ์ด๋ฅผ ๋ทฐ๋ชจ๋ธ์—์„œ ์ฒ˜๋ฆฌํ•ด์ฃผ๋ ค๊ณ  ํ•˜์˜€๋‹ค.!!

    class GetLikeStateUseCase @Inject constructor(private val likeRepository: LikeRepository) {
        operator fun invoke(reportId: String): Flow<Boolean> =
            flow {
                val result = likeRepository.checkLike(reportId = reportId)
                emit(result.getOrNull() ?: false)
            }.catch {
                Timber.e(it)
            }
    }
    

    ๊ฒฐ๊ณผ

    ๋”ฐ๋ž€~

    ๐Ÿ™‚‍↔๏ธ๋ฌธ์ œ ๋ฐœ์ƒ

    ๊ทธ๋Ÿฐ๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค. ์ข‹์•„์š” ์ƒํƒœ๋ฅผ ์•Œ๊ธฐ ์œ„ํ•ด์„œ๋Š” ๊ฒŒ์‹œ๊ธ€์˜ ์•„์ด๋””๋ฅผ ๋„˜๊ฒจ์ค˜์•ผํ•˜๋Š”๋ฐ ์ด๊ฑธ ์–ด๋–ป๊ฒŒ ๋„˜๊ฒจ์ค˜์•ผํ• ๊นŒ... 

     

    ์šฐ์„  ํ˜„์žฌ์™€ ๊ฐ™์ด ๋™์‹œ์— combine ํ•ด์ค„ ์ˆ˜ ์—†๊ฒŒ ๋˜์—ˆ๋‹ค.

    ์–ด๋–กํ•˜์ง€ ์–ด๋–กํ•˜์ง€

    ๊ณต์‹๋ฌธ์„œ๋ฅผ ๋ณธ ํ›„ ์ €์žฅ์†Œ ๊ฒฐํ•ฉ ๋ฐฉ์‹์— ๋Œ€ํ•ด ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. ์ด๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์—ฌ๋Ÿฌ ๊ฐœ์˜ usecase๋กœ ๋‚˜๋ˆ„์ง€ ์•Š๊ณ  ํ•˜๋‚˜์˜ usecase์—์„œ ์ฒ˜๋ฆฌํ•ด์ฃผ๋„๋ก ๋ณ€๊ฒฝํ•˜๋ฉด ์–ด๋–จ๊นŒ?

    ์™œ๋ƒํ•˜๋ฉด ์ข‹์•„์š” ์ƒํƒœ๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด์„œ๋Š” ๊ฐ์ƒ๋ฌธ์˜ id๊ฐ’์ด ํ•„์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค!

     

    ์ฐธ๊ณ ํ•œ ์ €์žฅ์†Œ ๊ฒฐํ•ฉ ์ฝ”๋“œ

    /**
     * This use case fetches the latest news and the associated author.
     */
    class GetLatestNewsWithAuthorsUseCase(
      private val newsRepository: NewsRepository,
      private val authorsRepository: AuthorsRepository,
      private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
    ) {
        suspend operator fun invoke(): List<ArticleWithAuthor> =
            withContext(defaultDispatcher) {
                val news = newsRepository.fetchLatestNews()
                val result: MutableList<ArticleWithAuthor> = mutableListOf()
                // This is not parallelized, the use case is linearly slow.
                for (article in news) {
                    // The repository exposes suspend functions
                    val author = authorsRepository.getAuthor(article.authorId)
                    result.add(ArticleWithAuthor(article, author))
                }
                result
            }
    }

     

    728x90