【问题标题】:Scarlet websocket in Android application with coroutine带有协程的Android应用程序中的Scarlet websocket
【发布时间】:2020-09-21 00:53:54
【问题描述】:

我正在尝试实现将与 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>
}

ChatSocketRepository

interface ChatSocketRepository {
    fun observeTest(): ReceiveChannel<String>
}

ChatSocketRepositoryImpl:

class ChatSocketRepositoryImpl(private val api: ChatSocketApi) : ChatSocketRepository {
    override fun observeTest(): ReceiveChannel<String> {
        return api.observeText()
    }
}

视图模型

class MyViewModel(private val chatSocketRepository: ChatSocketRepository) : BaseViewModel() {
    init {
        viewModelScope.launch {
            val text = chatSocketRepository.observeTest().consumeEach {
                Log.d("SOCKET", it.toString())
            }
        }
    }

【问题讨论】:

标签: android kotlin coroutine


【解决方案1】:

您已经获得了数据,并且您的数据是字符串,因为您声明了ReceiveChannel&lt;String&gt;,您可以使用接收到的数据并将其放入 LiveData。改为在 .consumeEach{} 方法中更改 livedata 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多