你可以使用LiveData来观察状态,当它是成功的时候就通知已经发生了成功
为您的州创建课程
sealed class NetworkLoadingState {
object OnLoading : NetworkLoadingState()
object OnSuccess : NetworkLoadingState()
data class OnError(val message: String) : NetworkLoadingState()
}
在你的 SetupGameViewModel 中创建一个 LiveData 实例来观察
class SetupGameViewModel : ViewModel() {
private var _loadState = MutableLiveData<Event<NetworkLoadingState>>()
val loadState: LiveData<Event<NetworkLoadingState>>
get() = _loadState
//Instead of `coroutineScope` use `viewModelScope`
fun createGame() {
// coroutineScope.launch {
viewModelScope.launch {
_loadState.value = Event(NetworkLoadingState.OnLoading)
val createGameRequest = CreateGameRequest(
gamePrice = gamePrice,
gameRules = gameRules,
playerOneGameName = playerOneGameName
)
var getPropertiesDeferred =
ParagonApi.retrofitService.createGameAsync(createGameRequest)
try {
_createGameResponse.value = getPropertiesDeferred.await()
//Here is code
_loadState.value = Event(NetworkLoadingState.OnSuccess)
} catch (e: Exception) {
_loadState.value = Event(NetworkLoadingState.OnError("Exception message here"))
}
}
}
}
现在在你的片段中
binding.startGameButton.setOnClickListener {
viewModel.createGame(this.view)
observeLoadingState()
}
private fun observeLoadingState() =
viewModel.loadState.observe(viewLifecycleOwner, EventObserver {
when (it) {
is NetworkLoadingState.OnLoading -> println("You can show loading indicator here or whatever to inform user that data is being loaded")
is NetworkLoadingState.OnSuccess -> println("Success now you can navigate")
is NetworkLoadingState.OnError -> println(it.errorMessage)
}
})
这是处理单个事件的事件类,否则当你的成功片段从后台堆栈弹出时,你将导航回成功屏幕
Event.kt
/*
a* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package your.package.name
import androidx.lifecycle.Observer
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
@Suppress("MemberVisibilityCanBePrivate")
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
//fun peekContent(): T = content
}
/**
* An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has
* already been handled.
*
* [onEventUnhandledContent] is *only* called if the [Event]'s contents has not been handled.
*/
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
override fun onChanged(event: Event<T>?) {
event?.getContentIfNotHandled()?.let {
onEventUnhandledContent(it)
}
}
}
想了解更多,可以visit my repo,喜欢就给个star吧。