代码之家  ›  专栏  ›  技术社区  ›  Feroz Siddiqui

android-如何使用viewmodel在oncreate中处理http调用,而oncreate不会在屏幕上被调用旋转?

  •  0
  • Feroz Siddiqui  · 技术社区  · 6 年前

    是的。在创建一个活动时加载数据的基本场景。因此,我试图加载数据,一旦我打开我的活动,但当我改变屏幕方向,它会再次调用。

    下面是我改造的rest客户

    public class MyRestApiClient {
        private static Retrofit retrofit = null;
    
        public static Retrofit getClient() {
    
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).connectTimeout(30,TimeUnit.SECONDS).readTimeout(30,TimeUnit.SECONDS).build();
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    
            retrofit = new Retrofit.Builder()
                    .baseUrl("http://localhost:8080/rest/")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
    
                    .build();
    
    
    
            return retrofit;
        }
    }
    

    下面是用于加载数据的resturl接口

       public interface MyRestUrlInterface {
        @GET("user/{user_id}")
            Call<Object> getData(@Path("user_id") String user_id);
        }
    

    下面是我的ViewModel类:

    public class MyViewModelObserver  extends ViewModel {
    
        private MutableLiveData<Object> httpCallBackObserver;
    
        public MutableLiveData<Object> getHttpCallBackObserver() {
            if (httpCallBackObserver == null) {
                httpCallBackObserver = new MutableLiveData<Object>();
            }
            return httpCallBackObserver;
        }
    }
    

    以下是我的活动代码:

    public class MyActivity extends AppCompatActivity {
     private static final String TAG = "MyActivity" ;
    
     MyRestUrlInterface restUrlInterface;
     public MyViewModelObserver myViewModelObserver;
    
    @Override   
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            restUrlInterface = MyRestApiClient.getClient().create(MyRestUrlInterface.class);
            myViewModelObserver = ViewModelProviders.of(this).get(MyViewModelObserver.class);
            myViewModelObserver.getHttpCallBackObserver().observe(this, getData());
            //load data via http
            Call<Object> call = restUrlInterface.getData("123");
            call.enqueue(new Callback<Object>() {
                @Override
                public void onResponse(Call<Object> call, Response<Object> response) {
                 myViewModelObserver.getHttpCallBackObserver().setValue(response.body());
                }
    
                @Override
                public void onFailure(Call<Object> call, Throwable t) {
    
                }
            });
    
            }
    
    
    private Observer<Object> getData(){
            return new Observer<Object>() {
                @Override
                public void onChanged(@Nullable final Object responseString) {
                    Log.d(TAG,"***** Loaded Data --- "+responseString);
    
                }
            };
        }
    }
    

    如何使用视图模型,使其在屏幕方向更改时不再进行http调用

    建议答案:

    public class MyViewModelObserver  extends ViewModel {
    
        private MutableLiveData<Object> httpCallBackObserver;
    
        public MutableLiveData<Object> getHttpCallBackObserver() {
            if (httpCallBackObserver == null) {
                httpCallBackObserver = new MutableLiveData<Object>();
                loadData();
    
            }
            return httpCallBackObserver;
        }
        private void loadData(){
        Call<Object> call = restUrlInterface.getData("123");
                call.enqueue(new Callback<Object>() {
                    @Override
                    public void onResponse(Call<Object> call, Response<Object> response) {
                     myViewModelObserver.getHttpCallBackObserver().setValue(response.body());
                    }
    
                    @Override
                    public void onFailure(Call<Object> call, Throwable t) {
    
                    }
                });
        }
    }
    
    0 回复  |  直到 6 年前