Skip to content

Commit

Permalink
add retrofit adapter:String and LiveData
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaofu committed Dec 9, 2018
1 parent b725143 commit fdbcc5b
Show file tree
Hide file tree
Showing 10 changed files with 247 additions and 0 deletions.
5 changes: 5 additions & 0 deletions app/src/main/java/com/xiaofu/student/BlankFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.xiaofu.lib.base.fragment.BaseFragment
import com.xiaofu.lib.base.http.HttpManager
import kotlinx.android.synthetic.main.fragment_blank.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -74,6 +75,10 @@ class BlankFragment : BaseFragment() {
// delay(1000L)
// }
// }

info { "abc???zhenshi Fragment=${HttpManager.INSTANCE.retrofit}" }


}

override fun bindListener() {
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/java/com/xiaofu/student/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import androidx.lifecycle.ViewModelProviders
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import com.xiaofu.lib.base.activity.BaseBindActivity
import com.xiaofu.lib.base.http.HttpManager
import com.xiaofu.student.databinding.ActivityMainBinding
import com.xiaofu.student.entity.movie
import com.xiaofu.student.net.ApiService
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import org.jetbrains.anko.info
import org.jetbrains.anko.toast
import org.jetbrains.anko.warn
import retrofit2.Call
import retrofit2.Callback
Expand Down Expand Up @@ -58,6 +60,25 @@ class MainActivity : BaseBindActivity<ActivityMainBinding>(), BottomNavigationBa
binding.mainTab.setTabSelectedListener(this)
replaceFragments(0)


info { "abc???zhenshi =${HttpManager.INSTANCE.retrofit}" }
HttpManager.INSTANCE.retrofit.create(ApiService::class.java)
.getMovieS()
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable) {
// cont.resumeWithException(t)
}

override fun onResponse(call: Call<String>, response: Response<String>) {
// log.info { "No.7 网络请求结束" }
if (response.body() is String){
toast("hahah S")
}
log.info(response.body())
// cont.resume(response.body()!!)
}
})

// launch {
// for (i in 1..50){
// log.info { "what launch:$this" }
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/xiaofu/student/net/ApiService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ import retrofit2.http.Query
interface ApiService {
@GET("boxoffice/day/query")
fun getMovie(@Query("key") key: String = "28d0461b30a6d", @Query("area") area: String = "CN"): Call<movie>

@GET("boxoffice/day/query")
fun getMovieS(@Query("key") key: String = "28d0461b30a6d", @Query("area") area: String = "CN"): Call<String>
}
3 changes: 3 additions & 0 deletions lib_base/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ dependencies {
}
api deps.dagger2.core

debugApi 'com.readystatesoftware.chuck:library:1.1.0'
releaseApi 'com.readystatesoftware.chuck:library-no-op:1.1.0'

kapt deps.kapt.arouter_compiler
kapt deps.kapt.databinding_compiler
kapt deps.kapt.glide
Expand Down
58 changes: 58 additions & 0 deletions lib_base/src/main/java/com/xiaofu/lib/base/http/HttpManager.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.xiaofu.lib.base.http

import android.content.Context
import com.readystatesoftware.chuck.ChuckInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
* 网络客户端
* Created by @author xiaofu on 2018/12/8.
*/
class HttpManager private constructor() {

private object Instance {
val instance = HttpManager()
}

companion object {
val INSTANCE = Instance.instance
}

/**
* 方便开发者调试接口,使用前先
*/
private var chuckInterceptor: ChuckInterceptor? = null

fun initChuck(context: Context) {
chuckInterceptor = ChuckInterceptor(context)
}

/**
* 配置OKHttp
*/
private fun createOkHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
chuckInterceptor?.let { chuck ->
builder.addInterceptor(chuck)
}
return builder.build()
}

val retrofit: Retrofit by lazy {
Retrofit.Builder()
.client(createOkHttpClient())
.baseUrl("http://apicloud.mob.com/")
.addConverterFactory(StringConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(LiveDataCallAdapterFactory.create())
.build()
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2017 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 com.xiaofu.lib.base.http


import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**
* A Retrofit adapter that converts the Call into a LiveData of ApiResponse.
* @param <R>
</R> */
class LiveDataCallAdapter<R>(private val responseType: Type) : CallAdapter<R, LiveData<R>> {

override fun responseType() = responseType

override fun adapt(call: Call<R>): LiveData<R> {
return object : LiveData<R>() {
private var started = AtomicBoolean(false)
override fun onActive() {
super.onActive()
if (started.compareAndSet(false, true)) {
call.enqueue(object : Callback<R> {
override fun onResponse(call: Call<R>, response: Response<R>) {
postValue(response.body())
}

override fun onFailure(call: Call<R>, throwable: Throwable) {
postValue(null)
}
})
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2017 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 com.xiaofu.lib.base.http

import androidx.lifecycle.LiveData
import retrofit2.CallAdapter
import retrofit2.CallAdapter.Factory
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class LiveDataCallAdapterFactory : Factory() {
override fun get(
returnType: Type,
annotations: Array<Annotation>,
retrofit: Retrofit
): CallAdapter<*, *>? {
if (Factory.getRawType(returnType) != LiveData::class.java) {
return null
}

if (returnType !is ParameterizedType) {
throw IllegalArgumentException("resource must be parameterized")
}

val type = Factory.getParameterUpperBound(0, returnType)
return LiveDataCallAdapter<Any>(type)
}

companion object {
fun create(): LiveDataCallAdapterFactory {
return LiveDataCallAdapterFactory()
}
}
}
22 changes: 22 additions & 0 deletions lib_base/src/main/java/com/xiaofu/lib/base/http/StringConverter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.xiaofu.lib.base.http

import okhttp3.ResponseBody
import retrofit2.Converter
import java.io.IOException


/**
*
* Created by @author xiaofu on 2018/12/8.
*/
class StringConverter : Converter<ResponseBody, String> {

@Throws(IOException::class)
override fun convert(value: ResponseBody): String? {
return value.string()
}

companion object {
val INSTANCE = StringConverter()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.xiaofu.lib.base.http

import retrofit2.Retrofit
import okhttp3.ResponseBody
import retrofit2.Converter
import java.lang.reflect.Type


/**
*
* Created by @author xiaofu on 2018/12/8.
*/
class StringConverterFactory : Converter.Factory() {

override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
return if (type == String::class.java) StringConverter.INSTANCE else null
}

companion object {
fun create(): StringConverterFactory {
return StringConverterFactory()
}
}

}
6 changes: 6 additions & 0 deletions versions.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ versions.arouter_compiler = "1.2.2"
versions.anko = "0.10.8"
versions.glide = "4.8.0"
versions.dagger2 = "2.19"
versions.rxjava2 = "2.2.4"

def deps = [:]

Expand Down Expand Up @@ -99,6 +100,11 @@ dagger2.core = "com.google.dagger:dagger:$versions.dagger2"
dagger2.compiler = "com.google.dagger:dagger-compiler:$versions.dagger2"
deps.dagger2 = dagger2

def rxjava2 = [:]
rxjava2.core = "io.reactivex.rxjava2:rxjava:$versions.rxjava2"
rxjava2.android = 'io.reactivex.rxjava2:rxandroid:2.1.0'
deps.rxjava2 = rxjava2

ext.deps = deps

static def addRepos(RepositoryHandler handler) {
Expand Down

0 comments on commit fdbcc5b

Please sign in to comment.