【发布时间】:2021-11-04 11:58:54
【问题描述】:
在 Jetpack Compose (1.0.4) 中,我使用 Tinder/Scarlet(2.4.0) 连接 WebSocket
implementation 'com.github.Tinder.Scarlet:scarlet:0.2.4'
implementation 'com.github.Tinder.Scarlet:scarlet-lifecycle-android:0.2.4'
implementation 'com.github.Tinder.Scarlet:scarlet-message-adapter-moshi:0.2.4'
implementation 'com.github.tinder.scarlet:scarlet-protocol-websocket-okhttp:0.2.4'
这就是我如何初始化和描述它的方式
@Provides
fun providesApplication(@ApplicationContext context: Context): MyApplication{
return context as MyApplication
}
@Provides
fun provideScarlet(
application: MyApplication,
client: OkHttpClient,
moshi: Moshi
): Scarlet {
val protocol = OkHttpWebSocket(
client,
OkHttpWebSocket.SimpleRequestFactory(
{ Request.Builder().url(baseWebSocketAddress).build() },
{ ShutdownReason.GRACEFUL }
)
)
val scarletConfiguration = Scarlet.Configuration(
messageAdapterFactories = listOf(MoshiMessageAdapter.Factory(moshi)),
streamAdapterFactories = listOf(FlowStreamAdapter.Factory()),
backoffStrategy = LinearBackoffStrategy(500),
lifecycle = AndroidLifecycle.ofApplicationForeground(
application
)
)
return Scarlet(protocol, scarletConfiguration)
}
@Singleton
@Provides
fun provideScarletMessagingService(scarlet: Scarlet): ScarletMessagingService {
return scarlet.create()
}
一切正常,包括事件、观察消息和其他问题,当我关闭/最小化应用程序时,websocket 即使在实现时也会关闭:
backoffStrategy = LinearBackoffStrategy(500),
lifecycle = AndroidLifecycle.ofApplicationForeground(
application
)
我正在像这样在我的视图模型上使用猩红色实例
@HiltViewModel
class MessagesViewModel
@Inject constructor(
private val scarletMessagingService: ScarletMessagingService) : ViewModel() {
init {
scarletMessagingService.observeMessage()
.flowOn(Dispatchers.IO)
.onEach {
Timber.d("A message from server $it.toString()")
}
.launchIn(viewModelScope)
}
}
我也有这个权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
【问题讨论】:
-
它是如何连接到 Jetpack Compose 的?我猜你没有提供最重要的代码。
-
@Jakoss 我更新了视图模型的其余部分并且效果很好,我认为其余的代码并不重要,我只想说我在 jetpack compose 中构建了我的项目仍然没有尝试在视图中显示消息
-
我猜关于 compose 的信息只是你问题中不必要的噪音,我会考虑删除它
标签: android websocket android-lifecycle