Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ViewModelを使用する #72

Open
aqua-ix opened this issue Mar 26, 2024 · 0 comments
Open

ViewModelを使用する #72

aqua-ix opened this issue Mar 26, 2024 · 0 comments

Comments

@aqua-ix
Copy link
Owner

aqua-ix commented Mar 26, 2024

LiveDataやStateFlow(Kotlin Coroutinesを使用する場合)を使ってデータの変更を監視し、UIに自動的に更新を通知する。

サンプルコード

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class ChatViewModel : ViewModel() {
    private val _messages = MutableLiveData<List<Message>>()
    val messages: LiveData<List<Message>> = _messages

    fun sendMessage(message: Message) {
        viewModelScope.launch {
            // メッセージ送信ロジックをここに記述
            // 例: _messages.value?.plus(message)などでメッセージリストを更新
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant