我正在尝试实现将与 websocket 一起使用的应用程序。所以我选择猩红。我可以在日志中看到来自服务器的响应,但我无法在我的 viewModel 中使用数据。怎么做?我正在使用 Koin + viewModel + 协程
Koin 模块
val networkModule = module {
single { createScarlet() }
single <ChatSocketRepository> {
ChatSocketRepositoryImpl(get())
}
}
private fun createScarlet(): ChatSocketApi {
val client = OkHttpClient.Builder()
.readTimeout(DataProviderImplementation.TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DataProviderImplementation.TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(DataProviderImplementation.TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.build()
return Scarlet.Builder()
.webSocketFactory(client.newWebSocketFactory("wss://demos.kaazing.com/echo"))
.addMessageAdapterFactory(GsonMessageAdapter.Factory())
.addStreamAdapterFactory(CoroutinesStreamAdapterFactory())
.build()
.create()
}
ChatSocketApi
interface ChatSocketApi {
@Receive
fun observeText(): ReceiveChannel<String>
}
ChatSocket存储库
interface ChatSocketRepository {
fun observeTest(): ReceiveChannel<String>
}
ChatSocketRepositoryImpl:
class ChatSocketRepositoryImpl(private val api: ChatSocketApi) : ChatSocketRepository {
override fun observeTest(): ReceiveChannel<String> {
return api.observeText()
}
}
View 模型
class MyViewModel(private val chatSocketRepository: ChatSocketRepository) : BaseViewModel() {
init {
viewModelScope.launch {
val text = chatSocketRepository.observeTest().consumeEach {
Log.d("SOCKET", it.toString())
}
}
}
最佳答案
您已经获得数据,并且您的数据是字符串,因为您声明了 ReceiveChannel<String>
您可以使用接收到的数据并将其放入 LiveData。更改 .consumeEach{}
中 livedata 的值代替方法。
关于android - 带有协程的Android应用程序中的Scarlet websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62153966/