Created
April 17, 2023 13:33
-
-
Save bgrebennikov/c20876054b3fa6860fe1d3e3e3eeca09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bgrebennikovv.github.wsexample | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.widget.Toast | |
import androidx.recyclerview.widget.LinearLayoutManager | |
import com.bgrebennikovv.github.wsexample.adapters.MessagesAdapter | |
import com.bgrebennikovv.github.wsexample.data.messages.MessageType | |
import com.bgrebennikovv.github.wsexample.databinding.ActivityMainBinding | |
import com.bgrebennikovv.github.wsexample.repositories.ChatRepository | |
import kotlinx.coroutines.* | |
import org.koin.android.ext.android.inject | |
import org.koin.core.component.KoinComponent | |
class MainActivity : AppCompatActivity(), KoinComponent { | |
private val binding by lazy { | |
ActivityMainBinding.inflate(layoutInflater) | |
} | |
private var scope = CoroutineScope(Dispatchers.IO) | |
private val messagesAdapter = MessagesAdapter() | |
private val chatRepository: ChatRepository by inject() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(binding.root) | |
binding.messagesRV.layoutManager = | |
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false).also { | |
it.stackFromEnd = true | |
} | |
binding.messagesRV.adapter = messagesAdapter | |
binding.sendBtn.setOnClickListener { | |
messagesAdapter.addMessage( | |
binding.messageBody.text.toString(), | |
MessageType.OUTGOING | |
) | |
scrollDown() | |
runBlocking { | |
chatRepository.sendMessage(binding.messageBody.text.toString()) | |
} | |
binding.messageBody.text = null | |
} | |
scope.launch { | |
chatRepository.receiveMessage { | |
runOnUiThread { | |
messagesAdapter.addMessage(it, MessageType.INCOMING) | |
scrollDown() | |
} | |
} | |
} | |
} | |
private fun scrollDown() { | |
binding.messagesRV.scrollToPosition(messagesAdapter.getItemsCount() - 1) | |
} | |
override fun onDestroy() { | |
scope.cancel() | |
super.onDestroy() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment