Skip to content

Commit

Permalink
feat: polling을 이용한 메시지 없데이트 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
gaeun5744 committed Dec 16, 2024
1 parent 4a8ef5a commit a2c2f41
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,19 @@ class ChatListFragment :
binding.vm = viewModel
}

override fun onStart() {
super.onStart()
viewModel.getChats()
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (hidden) {
viewModel.cancelPolling()
} else {
viewModel.getPollingChats()
}
}

private fun initAdapter() {
adapter = ChatListAdapter(this)
binding.rcvChatList.adapter = adapter
viewModel.getChats()
viewModel.getPollingChats()
viewModel.chats.observe(viewLifecycleOwner) { chats ->
adapter.submitList(chats)
}
Expand All @@ -43,7 +47,7 @@ class ChatListFragment :

private fun swipeEvent() {
binding.swipelayoutChatListRefresh.setOnRefreshListener {
viewModel.getChats()
viewModel.getPollingChats()
binding.swipelayoutChatListRefresh.isRefreshing = false
}
}
Expand All @@ -59,7 +63,7 @@ class ChatListFragment :
) { result ->

if (result.resultCode == LEAVE_CHAT_CODE) {
viewModel.getChats()
viewModel.getPollingChats()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import com.happy.friendogly.domain.usecase.GetChatListUseCase
import com.happy.friendogly.presentation.base.BaseViewModel
import com.happy.friendogly.presentation.ui.chatlist.uimodel.ChatListUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject

Expand All @@ -23,19 +26,30 @@ class ChatListViewModel
var memberId: Long = 0L
private set

private var pollJob: Job? = null

val isChatEmpty =
MediatorLiveData<Boolean>().apply {
addSource(_chats) {
value = it.isEmpty()
}
}

fun getChats() {
viewModelScope.launch {
getChatListUseCase.invoke().onSuccess { room ->
_chats.value = room.chatRooms.map { it.toUiModel() }
memberId = room.myMemberId
fun getPollingChats() {
pollJob?.cancel()
pollJob =
viewModelScope.launch {
while (this.isActive) {
getChatListUseCase.invoke().onSuccess { room ->
_chats.value = room.chatRooms.map { it.toUiModel() }
memberId = room.myMemberId
}
delay(1000)
}
}
}
}

fun cancelPolling() {
pollJob?.cancel()
}
}

0 comments on commit a2c2f41

Please sign in to comment.