我有一个基于MVVM架构的硬币改造项目。我要在注册该项目后在运行时使用“ viewmodel”打印数据并将“ token”的值添加到标题中。 但是我无法提供获取保存在SharedPreferences中的令牌所需的上下文结构。我该如何以最干净的方式处理它?</ p>
fun createNetworkClient(baseUrl: String) =
retrofitClient(baseUrl, httpClient())
private fun httpClient(): OkHttpClient {
val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
val clientBuilder = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
clientBuilder.addInterceptor(httpLoggingInterceptor)
}
clientBuilder.addInterceptor { chain ->
val newRequest = chain.request().newBuilder()
.addHeader( //I can't get token because there is no context here.
"Authorization", "Bearer ${PreferencesHelper.getInstance(context).token.toString()}"
)
.build()
chain.proceed(newRequest)
}
clientBuilder.readTimeout(120, TimeUnit.SECONDS)
clientBuilder.writeTimeout(120, TimeUnit.SECONDS)
return clientBuilder.build()
}
private fun retrofitClient(baseUrl: String, httpClient: OkHttpClient): Retrofit =
Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
AppModule
val appModule = module {
single {
androidApplication().getSharedPreferences("PREFERENCES", android.content.Context.MODE_PRIVATE)
}
single { createNetworkClient(BuildConfig.BASE_URL) }
single { (get() as Retrofit).create(Api::class.java) }
viewModel {
ContactViewModel(get())
}
}
MyContactActivity
private val contactList: ContactViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
viewModel = contactList
super.onCreate(savedInstanceState)
binding.adapter = ContactAdapter(this)
binding.layoutManager = LinearLayoutManager(this)
contactList.getContactList()
contactList.contactListLiveData.observe(this, Observer { list ->
if (list != null)
binding.adapter?.update(list)
})
}
答案 0 :(得分:1)
您可以创建Koin模块以提供“共享首选项”:
val sharedPreferencesModule = module {
single {
androidApplication().getSharedPreferences("PREFERENCES", android.content.Context.MODE_PRIVATE)
}
}
然后将Koin注入到生成Retrofit客户端的类中。
编辑
您需要修改createNetworkClient
方法签名:
fun createNetworkClient(baseUrl: String, preferences: SharedPreferences)
然后将其注入Koin:
val appModule = module {
single {
androidApplication().getSharedPreferences("PREFERENCES", android.content.Context.MODE_PRIVATE)
}
single { createNetworkClient(BuildConfig.BASE_URL, get()) }
...
}
然后,您将收到通过createNetworkClient
方法注入的共享首选项,只需要实现从共享首选项中检索令牌的逻辑即可。