StateFlow และ SharedFlow

StateFlow และ SharedFlow เป็น Flow API ที่ช่วยให้ Flow สามารถส่งการอัปเดตสถานะและส่งค่าไปยังผู้ใช้หลายรายได้อย่างมีประสิทธิภาพสูงสุด ซึ่งต่างจาก Cold Flow ตรงที่เป็น Hot Flow ที่ยังคงทำงานอยู่โดยไม่ขึ้นอยู่กับ Collector หากต้องการดูวิธีการทำงาน ความแตกต่างจากโฟลว์แบบเย็น และวิธีแปลงโฟลว์แบบเย็นด้วย stateIn และ shareIn โปรดดูโฟลว์แบบร้อนในเอกสารประกอบของ Kotlin หน้านี้ครอบคลุมวิธีใช้ StateFlow ในแอป Android ซึ่งได้แก่ การแสดงสถานะ UI จาก ViewModel, การรวบรวมสถานะ UI อย่างปลอดภัย และการเปรียบเทียบ StateFlow กับ LiveData

StateFlow

ใน Android StateFlow เหมาะอย่างยิ่งสำหรับคลาสที่ต้องรักษา สถานะที่เปลี่ยนแปลงได้ซึ่งสังเกตได้

จากตัวอย่างจาก Kotlin flows คุณสามารถแสดง StateFlow จาก LatestNewsViewModel เพื่อให้ View ฟังการอัปเดตสถานะ UI และทำให้สถานะหน้าจอคงอยู่หลังจากการเปลี่ยนแปลงการกำหนดค่าได้โดยอัตโนมัติ

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

    // Backing property to avoid state updates from other classes
    private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList()))
    // The UI collects from this StateFlow to get its state updates
    val uiState: StateFlow<LatestNewsUiState> = _uiState

    init {
        viewModelScope.launch {
            newsRepository.favoriteLatestNews
                // Update UI with the latest favorite news
                // Writes to the value property of MutableStateFlow,
                // adding a new element to the flow and updating all
                // of its collectors
                .collect { favoriteNews ->
                    _uiState.value = LatestNewsUiState.Success(favoriteNews)
                }
        }
    }
}

// Represents different states for the LatestNews screen
sealed class LatestNewsUiState {
    data class Success(val news: List<ArticleHeadline>) : LatestNewsUiState()
    data class Error(val exception: Throwable) : LatestNewsUiState()
}

คลาสที่มีหน้าที่อัปเดต MutableStateFlow คือผู้ผลิต และคลาสทั้งหมดที่รวบรวมจาก StateFlow คือผู้บริโภค

เมื่อผู้ใช้ใหม่เริ่มรวบรวมข้อมูลจากโฟลว์ ผู้ใช้จะได้รับสถานะล่าสุดในสตรีมและสถานะต่อๆ มา คุณจะเห็นลักษณะการทำงานนี้ในคลาสอื่นๆ ที่สังเกตได้ เช่น LiveData

ใน Jetpack Compose ให้รวบรวม StateFlow ด้วยฟังก์ชันที่ประกอบกันได้ collectAsStateWithLifecycle จากอาร์ติแฟกต์ androidx.lifecycle:lifecycle-runtime-compose ฟังก์ชันนี้จะแปลงโฟลว์เป็น Compose State และหยุดรวบรวมโดยอัตโนมัติเมื่อวงจรต่ำกว่า Lifecycle.State.STARTED ดูตัวอย่างได้ที่การรวบรวม Flow ที่รับรู้ถึงวงจร

ใน Views ให้รวบรวม StateFlow ภายใน repeatOnLifecycle เช่นเดียวกับโฟลว์อื่นๆ ดังนี้

class LatestNewsActivity : ComponentActivity() {
    private val latestNewsViewModel: LatestNewsViewModel = TODO() // getViewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
        // Start a coroutine in the lifecycle scope
        lifecycleScope.launch {
            // repeatOnLifecycle launches the block in a new coroutine every time the
            // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // Trigger the flow and start listening for values.
                // Note that this happens when lifecycle is STARTED and stops
                // collecting when the lifecycle is STOPPED
                latestNewsViewModel.uiState.collect { uiState ->
                    // New value received
                    when (uiState) {
                        is LatestNewsUiState.Success -> showFavoriteNews(uiState.news)
                        is LatestNewsUiState.Error -> showError(uiState.exception)
                    }
                }
            }
        }
    }
}

StateFlow, Flow และ LiveData

StateFlow และ LiveData มีความคล้ายคลึงกัน ทั้ง 2 คลาสเป็นคลาสตัวยึดข้อมูลที่สังเกตได้ และทั้ง 2 คลาสใช้รูปแบบที่คล้ายกันเมื่อใช้ในสถาปัตยกรรมแอป

อย่างไรก็ตาม โปรดทราบว่า StateFlow และ LiveData มีลักษณะการทำงานที่แตกต่างกัน ดังนี้

  • StateFlow กำหนดให้ต้องส่งสถานะเริ่มต้นไปยังตัวสร้าง แต่ LiveData ไม่กำหนด
  • LiveData.observe() จะยกเลิกการลงทะเบียนผู้ใช้โดยอัตโนมัติเมื่อมุมมองเข้าสู่สถานะ STOPPED ในขณะที่การรวบรวมจาก StateFlow หรือโฟลว์อื่นๆ จะไม่หยุดรวบรวมโดยอัตโนมัติ หากต้องการให้ทำงานเหมือนเดิม ให้รวบรวมโฟลว์ด้วย collectAsStateWithLifecycle ใน Compose หรือจากบล็อก Lifecycle.repeatOnLifecycle ใน Views

แหล่งข้อมูลเพิ่มเติมเกี่ยวกับขั้นตอน