我的 MVVM 应用程序有两个请求:
fun fetchStrings(lang: String, callBack: (res: JsonObject?) -> Unit) {
job = CoroutineScope(Dispatchers.IO).launch {
val array = JsonArray().apply { strings.forEach { item -> add(item) } }
val jsonObject = JsonObject().apply {
addProperty("lang", lang)
add("ids", array)
}
val response = mainRepository.getStrings(jsonObject)
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
callBack.invoke(response.body())
} else {
callBack.invoke(null)
}
}
}
}
和:
fun getUserFiles(requestBody: RequestBody? = null, callBack: (res: Any) -> Unit) {
job = CoroutineScope(Dispatchers.IO).launch {
val response = requestBody?.let { mainRepository.getUserFiles(it) }
withContext(Dispatchers.Main) {
if (response?.isSuccessful == true) {
callBack.invoke(response.body()!!)
} else {
response?.message()?.let { callBack.invoke(it) }
}
}
}
}
他们都在一个视图模型中。这个视图模型使用 mainRepository 和这些方法:
class MainRepository constructor(private val retrofitService: RetrofitService) {
suspend fun getUserFiles(requestBody: RequestBody) = retrofitService.getUserFiles(requestBody)
suspend fun getStrings(jsonObject: JsonObject) = retrofitService.getStrings(jsonObject)
}
改装服务:
companion object {
var retrofitService: RetrofitService? = null
fun getInstance(mint: Boolean): RetrofitService {
var isMint = true
val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.MINUTES)
.callTimeout(10, TimeUnit.MINUTES)
.writeTimeout(10, TimeUnit.MINUTES)
.readTimeout(10, TimeUnit.MINUTES)
.connectionPool(ConnectionPool(0, 5, TimeUnit.SECONDS))
.dispatcher(Dispatcher().apply {
maxRequests = 1
})
.protocols(listOf(Protocol.HTTP_1_1))
.build()
client.dispatcher.cancelAll()
val retrofit = Retrofit.Builder()
.baseUrl(if (mint) BuildConfig.MINT_URL else BuildConfig.API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofitService = retrofit.create(RetrofitService::class.java)
return retrofitService!!
}
}
问题是这些方法有两个不同的请求 URL,由这个条件管理
if (isMint) BuildConfig.MINT_URL else BuildConfig.API_URL
当我进行活动时:
val retrofitService = RetrofitService.getInstance(false)
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(
this,
AppVMFactory(mainRepository)
)[RequestsCore::class.java]
在这里改变
RetrofitService.getInstance(false)
true/false 我看到这个值没有改变。我试图清除视图模型:
viewModelStoreOwner.viewModelStore.clear()
但这没有帮助。我试图在以下位置添加直接条件:
.baseUrl(if (mint) BuildConfig.MINT_URL else BuildConfig.API_URL)
这将取决于请求 url,但它也没有帮助。也尝试过这样的方式:
viewModelStoreOwner.viewModelStore.keys().forEach {
viewModelStoreOwner.viewModelStore[it]?.viewModelScope?.coroutineContext?.cancel()
}
我能看到的唯一方法是使用类似存储库创建单独的 Viewmodel。也许我们有一些方法可以在一个 viewmodelstoreowner 的上下文中重置 viewmodel 的所有值?