android - 带有协程的Android应用程序中的Scarlet websocket

标签 android kotlin coroutine

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

相关文章:

android - findviewbyid() 在 Eclipse 中的自定义适配器中返回 null

java - 无法创建 AndroidViewModel 子类的实例

kotlin - ArraysJVM.kt VS _ArraysJVM.kt

python - 从基于生成器的协程转换为 native 协程

python-asyncio:走协程链

android - 何时使用后值

java - 从 Java 类中引用 Android View

java - 为什么 Kotlin JDK8 也在类路径中包含 Kotlin JDK7?

android - HiltWorkerFactory : Configure WorkManagerInitializer at AppStartup

android - Xamarin.Android 中的 DiffUtil